为了账号安全,请及时绑定邮箱和手机立即绑定

片段中的findViewById

片段中的findViewById

白板的微信 2019-06-04 15:59:44
片段中的findViewById我试图在片段中创建ImageView,该片段将引用我在XML中为片段创建的ImageView元素。但是,findViewById方法只在扩展活动类时才有效。还有我也可以用在片段里的吗?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方法上有一个错误,该错误声明该方法是未定义的。
查看完整描述

3 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

Fragment你要上的课onViewCreated()应该始终初始化视图的重写方法,就像在此方法中获得视图对象一样,您可以使用该方法找到视图如下:

@Overridepublic 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);}

切记在破片的情况下onViewCreated()如果返回NULL或super.onCreateView()从…onCreateView()方法。默认情况下,它将被调用。ListFragmentListFragment回归FrameLayout默认情况下。

注意:您可以在类中的任何地方获得片段视图,方法是getView()一次onCreateView()已经成功执行了。E.

getView().findViewById("your view id");


查看完整回答
反对 回复 2019-06-04
  • 3 回答
  • 0 关注
  • 544 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信