片段中的findViewById

我试图在一个Fragment中创建一个ImageView,该ImageView引用我在Fragment的XML中创建的ImageView元素。 但是,仅当我扩展Activity类时, findViewById方法才有效。 无论如何,我也可以在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方法上有一个错误,指出该方法未定义。


#1楼

我意识到这是一个古老的问题,但是普遍的答案仍有待改进。

问题尚不清楚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;
    }
}

#2楼

同意在视图上调用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;
}

#3楼

使用getView()返回片段的视图,然后可以调用findViewById()来访问片段视图中的任何视图元素。


#4楼

您也可以在onActivityCreated方法中执行此操作。

public void onActivityCreated(Bundle savedInstanceState) { 
      super.onActivityCreated(savedInstanceState);
}

就像他们在这里所做的一样: http : //developer.android.com/reference/android/app/Fragment.html (在API级别28中已弃用)

getView().findViewById(R.id.foo);

getActivity().findViewById(R.id.foo);

是可能的。


#5楼

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

在片段的情况下&#x

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值