本文介绍了findViewById在片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个片段,将参照我的XML中的片段所创建的ImageView的元素的ImageView的。但是, findViewById
方法只能如果我向一个Activity类。反正是有它的,我可以在片段使用它呢?
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. However, the findViewById
method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?
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);
}
}
在 findViewById
方法上有一个错误,指出该方法是不确定的。
The findViewById
method has an error on it which states that the method is undefined.
推荐答案
使用 getView()。这将返回根视图的片段,这个你可以叫 findViewById()
。
Use getView(). This will return the root view for the fragment, with this you can call findViewById()
.
ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
这篇关于findViewById在片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!