我正在尝试在 Fragment 中创建一个 ImageView,它将引用我在 XML 中为 Fragment 创建的 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 方法上有一个错误,指出该方法未定义。
Best Answer-推荐答案
使用getView()或来自实现 onViewCreated 的 View 参数方法。它返回 fragment 的 Root View (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() 方法的 fragment 。
关于android - fragment 中的 findViewById,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/6495898/
|