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


当前回答

非常简单的方法:

 @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View fragmentView = inflater.inflate(R.layout.testclassfragment, container, false);
            ImageView imageView = (ImageView)fragmentView.findViewById(R.id.my_image);
            return fragmentView;
       }

其他回答

你需要膨胀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;
}

你必须放大视图

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

在onCreateView方法中

1)首先你必须膨胀你想要添加的布局/视图 如。LinearLayout

LinearLayout ll = inflater.inflate(R.layout.testclassfragment, container, false);

2)然后你可以从布局中找到你的imageView id

ImageView imageView = (ImageView)ll.findViewById(R.id.my_image);

3)返回膨胀的布局

return ll;
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()方法,它可能会导致nullPointerException,因为它返回根视图,它将是onCreateView()方法之后的某个视图。

试试这个:

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

return v;