片段中的 findViewById [英] findViewById in Fragment

查看:24
本文介绍了片段中的 findViewById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Fragment 中创建一个 ImageView,它将引用我在 XML 中为 Fragment 创建的 ImageView 元素.但是,findViewById 方法仅在我扩展 Activity 类时才有效.无论如何,我也可以在 Fragment 中使用它吗?

I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

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 方法有一个错误,表明该方法未定义.

The findViewById method has an error on it which states that the method is undefined.

推荐答案

使用 getView() 或实现 onViewCreated 方法的 View 参数.它返回片段的根视图(onCreateView() 方法返回的视图).有了这个,你可以调用 findViewById().

Use getView() or the View parameter from implementing the onViewCreated method. It returns the root view for the fragment (the one returned by onCreateView() method). With this you can call 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()方法.

As getView() works only after onCreateView(), you can't use it inside onCreate() or onCreateView() methods of the fragment .

这篇关于片段中的 findViewById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆