片段中的findViewById

扶醉桌前 提交于 2020-08-13 00:01:43

问题:

I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. 我试图在一个Fragment中创建一个ImageView,该ImageView引用我在Fragment的XML中创建的ImageView元素。 However, the findViewById method only works if I extend an Activity class. 但是,仅当我扩展Activity类时, findViewById方法才有效。 Is there anyway of which I can use it in Fragment as well? 无论如何,我也可以在Fragment中使用它吗?

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ImageView imageView = (ImageView)findViewById(R.id.my_image);
        return inflater.inflate(R.layout.testclassfragment, container, false);
    }
}

The findViewById method has an error on it which states that the method is undefined. findViewById方法上有一个错误,指出该方法未定义。


解决方案:

参考一: https://stackoom.com/question/RFsY/片段中的findViewById
参考二: https://oldbug.net/q/RFsY/findViewById-in-Fragment
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!