我试图在一个片段中创建一个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方法有一个错误,说明该方法未定义。
在onCreateView方法中
1)首先你必须膨胀你想要添加的布局/视图
如。LinearLayout
LinearLayout ll = inflater.inflate(R.layout.testclassfragment, container, false);
2)然后你可以从布局中找到你的imageView id
ImageView imageView = (ImageView)ll.findViewById(R.id.my_image);
3)返回膨胀的布局
return ll;
在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");
根据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;
}