我试图在一个片段中创建一个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方法有一个错误,说明该方法未定义。


当前回答

.commit()之后的事务计时也可能导致此问题

我得到了同样的问题(在片段中的视图无法到达)。原因是,在(FragmentTransaction).commit() -之后,视图没有在UI中被激活。在.commit()之后,事务发生时没有保证;它只是排队。所以我添加了一个(FragmentManager). executependingtransactions()来强制完成事务。之后,引用视图就可以正常工作了!

其他回答

getView()将给出根视图

View v = getView().findViewByID(R.id.x); 

试试这个:

View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);

return v;

同意在视图上调用findViewById()。

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;
}

我知道这是一个老问题,但普遍的答案让人感到有些不足。

问题是不清楚imageView需要什么-我们是将它作为视图传递回去,还是仅仅为以后保存一个引用?

无论哪种方式,如果ImageView来自于膨胀布局,正确的做法是:

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;
    }
}

你可以调用findViewById()的活动对象,你得到的公共void onAttach(活动活动)方法在你的片段。

将Activity保存为一个变量,例如:

在Fragment类中: private Activity mainActivity; onAttach()方法中: this.mainActivity =活动;

最后通过变量执行每个findViewById: mainActivity.findViewById (R.id.TextView);