我试图在一个片段中创建一个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方法有一个错误,说明该方法未定义。
在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");
布局增压机进入图片这里。布局扩展器是一个使我们能够在java代码中使用XML视图的类。因此,您可以使用以下代码在变量v中扩展根xml视图。然后使用v,你可以找到根视图v的子视图。
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;
}
}
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);
}