在Fragment中使用findViewById函数。
在Fragment中使用findViewById函数。
我正在尝试在Fragment中创建一个ImageView,它将引用我在Fragment 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
方法上有一个错误,指出该方法未定义。
admin 更改状态以发布 2023年5月23日
你需要充气Fragment的视图并在返回的View
上调用findViewById()
。
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()或在实现onViewCreated
方法时使用视图参数。它返回片段的根视图(由onCreateView()
方法返回)。使用此方法,您可以调用findViewById()
。
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { ImageView imageView = (ImageView) getView().findViewById(R.id.foo); // or (ImageView) view.findViewById(R.id.foo);
由于getView()
仅在onCreateView()
之后起作用,因此无法在片段的onCreate()
或onCreateView()
方法中使用它。