android开发中RadioGroup动态添加组件的时候checkedId自动累加的解决方案

radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton=findViewById(group.getCheckedRadioButtonId());
                String answer=radioButton.getText().toString().substring(0,1);
                listUserAnswerRecordDatas.get(currentQuestionId-1).set_t_useranswer(answer);
                //Toast.makeText(PractiseActivity.this,"您选择了:"+radioButton.getText().toString(),Toast.LENGTH_SHORT).show();
            }
        });

问题:向一个RadioGroup中动态的添加一批RadioButton之后,即使进行了removeallviews()方法,这个checkedId仍然是在不断的累加,这样导致了没法获取正确的RadioButton。

解决方案:可以采用RadioGroup的getCheckedRadioButtonId( )方法来获取被选中的RadioButton。

发布了240 篇原创文章 · 获赞 78 · 访问量 36万+
展开阅读全文

fragment添加动态单选框radiogroup.addView(button)报错为空。

07-02

在fragment中动态添加单选框时(参照的https://blog.csdn.net/shihuiyun/article/details/52935392), radiogroup.addView(button);报错Attempt to invoke virtual method 'void android.widget.RadioGroup.addView(android.view.View)' on a null object reference;我的定义radiobutton了啊 ``` public void initViewTwo(){ RadioGroup radiogroup=(RadioGroup)getActivity().findViewById(R.id.gadiogroup); addview(radiogroup); } public List<String> getListSize(){ List<String>list=new ArrayList<String>(); list.add("服装33333"); list.add("玩具44444"); list.add("饰品5555"); list.add("饰品6666"); list.add("文具7777"); list.add("文具8888"); list.add("文具9999"); return list; } //动态添加视图 public void addview(RadioGroup radiogroup){ int index=0; for(String ss:getListSize()){ RadioButton button=new RadioButton(getActivity()); setRaidBtnAttribute(button,ss,index); radiogroup.addView(button); LinearLayout.LayoutParams layoutParams= (LinearLayout.LayoutParams) button .getLayoutParams(); layoutParams.setMargins(0, 0, DensityUtil.dpToPx(getActivity(),10), 0);//4个参数按顺序分别是左上右下 button.setLayoutParams(layoutParams); index++; } } @SuppressLint("ResourceType") private void setRaidBtnAttribute(final RadioButton codeBtn, String btnContent, int id ){ if( null == codeBtn ){ return; } // codeBtn.setBackgroundResource(R.drawable.radio_select); codeBtn.setTextColor(this.getResources().getColorStateList(R.drawable.top_select)); codeBtn.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT)); //codeBtn.setTextSize( ( textSize > 16 )?textSize:24 ); codeBtn.setId( id ); codeBtn.setText( btnContent ); //codeBtn.setPadding(2, 0, 2, 0); codeBtn.setGravity( Gravity.CENTER ); codeBtn.setOnClickListener( new OnClickListener( ) { @Override public void onClick(View v) { Toast.makeText(getActivity(), codeBtn.getText().toString(), Toast.LENGTH_SHORT).show(); } }); //DensityUtilHelps.Dp2Px(this,40) LinearLayout.LayoutParams rlp = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT , DensityUtil.dpToPx(getActivity(),25) ); codeBtn.setLayoutParams( rlp ); } ``` 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览