Android --- RecycleView获取第 i 个 item 里面的控件并进行赋值
生活随笔
收集整理的這篇文章主要介紹了
Android --- RecycleView获取第 i 个 item 里面的控件并进行赋值
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
今天些項(xiàng)目的時(shí)候遇到了這樣的問題,我想要操作 RecycleView 中某個(gè) item 里面的子控件,通過度娘找到了一些方法,但是感覺都不全,下面整理一下:
直接上代碼:
View view = manager.findViewByPosition(0);RelativeLayout relativeLayout = (RelativeLayout)view; //獲取布局中任意控件對(duì)象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);上面這種做法會(huì)報(bào)錯(cuò)
會(huì)報(bào)空指針異常,因?yàn)槟銊倓傔M(jìn)入這個(gè) Activity 或者 Fragment 的時(shí)候還沒有加載完此 View 所以我們要加一個(gè)判斷,代碼如下:
rv_subject.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {// 默認(rèn)選中第一個(gè)View view = manager.findViewByPosition(0);RelativeLayout relativeLayout = (RelativeLayout)view; //獲取布局中任意控件對(duì)象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);}});還要注意一點(diǎn)是,上面這串代碼的位置一定要放正確,要不也會(huì)報(bào)錯(cuò),提示沒有這個(gè)方法,所放的位置為,你找到該控件的下面,代碼如下:
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() {// 默認(rèn)選中第一個(gè)View view = manager.findViewByPosition(0);RelativeLayout relativeLayout = (RelativeLayout)view; //獲取布局中任意控件對(duì)象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);}});}以上就是我的總結(jié)
附上參考博主鏈接: https://blog.csdn.net/d06110902002/article/details/68495853?utm_source=blogxgwz8
總結(jié)
以上是生活随笔為你收集整理的Android --- RecycleView获取第 i 个 item 里面的控件并进行赋值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android --- 选项卡背景样式,
- 下一篇: Android --- RecycleV