我试图在一个片段中创建一个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方法有一个错误,说明该方法未定义。
方法getView()不会在OnCreate和类似方法之外的片段上工作。
你有两种方法,将视图传递给oncreate上的函数(这意味着你只能在创建视图时运行你的函数)或将视图设置为变量:
private View rootView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_contatos, container, false);
}
public void doSomething () {
ImageView thumbnail = (ImageView) rootView.findViewById(R.id.someId);
}
在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");
我知道这是一个老问题,但普遍的答案让人感到有些不足。
问题是不清楚imageView需要什么-我们是将它作为视图传递回去,还是仅仅为以后保存一个引用?
无论哪种方式,如果ImageView来自于膨胀布局,正确的做法是:
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
}
注意,如果你使用getView()方法,它可能会导致nullPointerException,因为它返回根视图,它将是onCreateView()方法之后的某个视图。