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


当前回答

还有一个方法叫做onViewCreated。

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
}

其他回答

使用getView()或实现onViewCreated方法的View参数。它返回片段的根视图(由onCreateView()方法返回的)。这样你就可以调用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()方法中使用它。

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

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

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

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

Use

imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);

imageview = (ImageView) getActivity().findViewById(R.id.imageview1);

会有用的

在Fragment类中,你会得到onViewCreated()覆盖方法,你应该总是初始化你的视图,因为在这个方法中,你得到视图对象,使用它你可以像这样找到你的视图:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.findViewById(R.id.yourId).setOnClickListener(this);

    // or
    getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}

永远记住,在Fragment的情况下,如果你从onCreateView()方法返回null或super.onCreateView(), onViewCreated()方法不会自动调用。 它将在ListFragment作为ListFragment返回FrameLayout的情况下被默认调用。

注意:一旦onCreateView()成功执行,你可以使用getView()在类的任何地方获得片段视图。 即。

getView().findViewById("your view id");
//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;