我试图在一个片段中创建一个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;
注意:
从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;
}