我试图在一个片段中创建一个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中,我们需要那个窗口的视图,这样我们就可以创建这个Fragment的onCreateView。

然后获取视图并使用它来访问该视图元素的每个视图id ..

  class Demo extends Fragment
    {
        @Override
        public View onCreateView(final LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
        {
            View view =inflater.inflate(R.layout.demo_fragment, container,false);
            ImageView imageview=(ImageView)view.findViewById(R.id.imageview1);

            return view;
        }
    }

其他回答

使用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()。

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

最简单的方法就是用黄油刀 这样你就可以像下面描述的那样通过@OnClick()添加尽可能多的Onclciklisteners:

public class TestClass extends Fragment {
    @BindView(R.id.my_image) ImageView imageView;
    @OnClick(R.id.my_image)
    public void my_image_click(){
        yourMethod();
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.testclassfragment, container, false);
        ButterKnife.bind(getActivity,view);
        return view;
    }
}

注意:

从API级别26开始,您也不需要专门强制转换findViewById的结果,因为它对其返回类型使用推断。

现在你可以简单地做,

public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container, 
                         Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.testclassfragment, container, false);
     ImageView imageView =  view.findViewById(R.id.my_image); //without casting the return type
     return view;
}