Android --- RecycleView获取第 i 个 item 里面的控件并进行赋值
生活随笔
收集整理的這篇文章主要介紹了
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() {@Overridepublic 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() {@Overridepublic 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
總結
以上是生活随笔為你收集整理的Android --- RecycleView获取第 i 个 item 里面的控件并进行赋值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android --- 选项卡背景样式,
- 下一篇: Android --- RecycleV