我试图在一个片段中创建一个ImageView,它将引用我在XML中为片段创建的ImageView元素。但是,findViewById方法仅在扩展Activity类时有效。我是否也可以在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);
}
}
findViewById方法有一个错误,说明该方法未定义。
根据API级别11的文档
参考,在Back Stack
http://developer.android.com/reference/android/app/Fragment.html
短代码
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
1)声明布局文件。
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
return inflate(R.layout.myfragment, container, false);
}
2)然后,获取视图的id
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView nameView = (TextView) view.findViewById(R.id.textview1);
}
注意:
从API级别26开始,您也不需要专门强制转换findViewById的结果,因为它对其返回类型使用推断。
现在你可以简单地做,
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = view.findViewById(R.id.my_image); //without casting the return type
return view;
}
使用gradle skeleton插件,它会自动生成视图持有者类,并引用到你的布局。
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyLayout myLayout = new MyLayout(inflater, container, false);
myLayout.myImage.setImageResource(R.drawable.myImage);
return myLayout.view;
}
}
现在假设你在my_layout.xml文件中声明了一个ImageView,它会自动为你生成myLayout类。
在Fragment类中,你会得到onViewCreated()覆盖方法,你应该总是初始化你的视图,因为在这个方法中,你得到视图对象,使用它你可以像这样找到你的视图:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
// or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
永远记住,在Fragment的情况下,如果你从onCreateView()方法返回null或super.onCreateView(), onViewCreated()方法不会自动调用。
它将在ListFragment作为ListFragment返回FrameLayout的情况下被默认调用。
注意:一旦onCreateView()成功执行,你可以使用getView()在类的任何地方获得片段视图。
即。
getView().findViewById("your view id");