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


当前回答

你也可以在onActivityCreated方法中做。

public void onActivityCreated(Bundle savedInstanceState) { 
      super.onActivityCreated(savedInstanceState);
}

就像他们在这里做的:http://developer.android.com/reference/android/app/Fragment.html(在API级别28中已弃用)

getView().findViewById(R.id.foo);

and

getActivity().findViewById(R.id.foo);

是有可能的。

其他回答

使用gradle skeleton插件,它会自动生成视图持有者类,并引用到你的布局。

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MyLayout myLayout = new MyLayout(inflater, container, false);
        myLayout.myImage.setImageResource(R.drawable.myImage);
        return myLayout.view;
    }
}

现在假设你在my_layout.xml文件中声明了一个ImageView,它会自动为你生成myLayout类。

你需要膨胀Fragment的视图,并在它返回的视图上调用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;
}

布局增压机进入图片这里。布局扩展器是一个使我们能够在java代码中使用XML视图的类。因此,您可以使用以下代码在变量v中扩展根xml视图。然后使用v,你可以找到根视图v的子视图。

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

试试这个:

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

return v;

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

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