Java代码添加RadioButton

  • xml:

         
                 ... ...
         
    
  • java:
    final int tabNum = 3;
    tabLayout = findViewById(R.id.lay_tab);
    RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(org.xclcharts.common.DensityUtil.getScreenWidth(_context) / tabNum, ViewGroup.LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER;
    for (int i = 0; i < tabNum; i++) {
    final RadioButton rb1 = new RadioButton(_context);
    rb1.setBackgroundResource(android.R.color.transparent);
    rb1.setButtonDrawable(android.R.color.transparent);
    rb1.setLayoutParams(params);
    rb1.setGravity(Gravity.CENTER);
    // 文本颜色选择,引用res-xml
    ColorStateList csl = getResources().getColorStateList(R.color.color_menu_text);
    if (csl != null) {
    rb1.setTextColor(csl);
    }
    rb1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
    StateListDrawable listDrawable = new StateListDrawable();
    switch (i) {
    case 0:
    rb1.setText(R.string.home);
    listDrawable = (StateListDrawable) getResources().getDrawable(R.drawable.selector_home);
    break;
    case 1:
    rb1.setText(R.string.school);
    listDrawable = (StateListDrawable) getResources().getDrawable(R.drawable.selector_work);
    break;
    case 2:
    rb1.setText(R.string.mine);
    listDrawable = (StateListDrawable) getResources().getDrawable(R.drawable.selector_user);
    break;
    }

         final int finalI = i;
         rb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
             @Override
             public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                 if (b) {
                     if (finalI == 1 && !MainApplication.isLogin()) {
                         //处理学院未登录点击
                         SharedPreferences sp = getSharedPreferences("XueXi", MODE_PRIVATE);
                         SharedPreferences.Editor edit = sp.edit();
                         edit.putString("xuexi", "1");
                         edit.putString("pdhome", "110");
                         edit.commit();
                         Intent in = new Intent();
                         in.setClass(_context, LoginActivity.class);
                         startActivity(in);
                     } else {
                         showFragment(fragments.get(finalI), "fragment" + finalI);
                         curIndex = finalI;
                     }
                 }
             }
         });
         setRbDrawable(rb1, listDrawable);
         tabLayout.addView(rb1);
     }
    

你可能感兴趣的:(View)