Android --- RecycleView获取第 i 个 item 里面的控件并进行赋值

今天些项目的时候遇到了这样的问题,我想要操作 RecycleView 中某个 item 里面的子控件,通过度娘找到了一些方法,但是感觉都不全,下面整理一下:

直接上代码:

  View view = manager.findViewByPosition(0);
  RelativeLayout relativeLayout = (RelativeLayout)view;		//获取布局中任意控件对象
  TextView subjectName = relativeLayout.findViewById(R.id.tv_subject_name);
  LinearLayout subjectBag = relativeLayout.findViewById(R.id.rl_subject);
  subjectName.setTextSize(14);
  subjectName.getPaint().setFakeBoldText(true);
  subjectBag.setBackgroundResource(R.drawable.bag_subject_item_selected);

上面这种做法会报错

会报空指针异常,因为你刚刚进入这个 Activity 或者 Fragment 的时候还没有加载完此 View 所以我们要加一个判断,代码如下:


 rv_subject.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver
         .OnGlobalLayoutListener() {
     @Override
     public void onGlobalLayout() {
         // 默认选中第一个
         View view = manager.findViewByPosition(0);
         RelativeLayout relativeLayout = (RelativeLayout)view;		//获取布局中任意控件对象
         TextView subjectName = relativeLayout.findViewById(R.id.tv_subject_name);
         LinearLayout subjectBag = relativeLayout.findViewById(R.id.rl_subject);
         subjectName.setTextSize(14);
         subjectName.getPaint().setFakeBoldText(true);
         subjectBag.setBackgroundResource(R.drawable.bag_subject_item_selected);
     }
 });

还要注意一点是,上面这串代码的位置一定要放正确,要不也会报错,提示没有这个方法,所放的位置为,你找到该控件的下面,代码如下:

public void initView() {
        subjectArray = getContext().getResources().getStringArray(R.array.subjects);
        rv_subject = view.findViewById(R.id.rv_subject);
		rv_subject.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver
		         .OnGlobalLayoutListener() {
		     @Override
		     public void onGlobalLayout() {
		         // 默认选中第一个
		         View view = manager.findViewByPosition(0);
		         RelativeLayout relativeLayout = (RelativeLayout)view; //获取布局中任意控件对象
		         TextView subjectName = relativeLayout.findViewById(R.id.tv_subject_name);
		         LinearLayout subjectBag = relativeLayout.findViewById(R.id.rl_subject);
		         subjectName.setTextSize(14);
		         subjectName.getPaint().setFakeBoldText(true);
		         subjectBag.setBackgroundResource(R.drawable.bag_subject_item_selected);
		     }
		});
    }

以上就是我的总结

附上参考博主链接: https://blog.csdn.net/d06110902002/article/details/68495853?utm_source=blogxgwz8

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁同学与Android

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值