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


当前回答

在Fragment类中,我们得到onViewCreated()重写方法,我们应该总是初始化我们的视图,因为在这个方法中我们得到视图对象。使用这个对象,我们可以像下面这样找到我们的视图:

class MyFragment extends Fragment {
    private ImageView imageView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.my_fragment_layout, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //initialize your view here for use view.findViewById("your view id")
        imageView = (ImageView) view.findViewById(R.id.my_image);
    }
}

其他回答

首先获取片段视图,然后从这个视图获取ImageView。

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

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

问题是不清楚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;
    }
}
ImageView imageView;
public View onCreateView(LayoutInflater inflater, 
                     ViewGroup container, 
                     Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.testclassfragment, container, false);
 imageView = view.findViewById(R.id.my_image);
 return view;

}

我喜欢一切都有条理。你可以这样做。

第一个初始化视图

private ImageView imageView;

然后覆盖OnViewCreated

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findViews(view);
    }

然后添加一个void方法来查找视图

private void findViews(View v) {
    imageView = v.findViewById(R.id.img);
}
//here you can do it by
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
  {
    // Inflate the layout for this fragment
    final View view =  inflater.inflate(R.layout.fragment_apple, container, 
 false);
    ist = view.findViewById(R.id.linearLink);
    second = view.findViewById(R.id.linearPhone);
    return view;