Android RadioButton实现多行布局

因为RadioGroup继承自LinearLayout,所以所有RadioButton要么纵向排成一行,要么横向排成一行。如果想把RadioButton分成两行,可能会想到使用下面的XML布局,就是用两个LinearLayout。




    

    

        

            

            

        

        

            

            

        

    


上面的运行结果如下图这样,可以把RadioButton分为多行,但是这样的RadioGroup会失去单选的功能。因为所有RadioButton必须作为RadioGroup的子View才行。


Android RadioButton实现多行布局_第1张图片

于是就想了个注意,如果要把所有RadioButton放在两行,就弄两个RadioGroup。然后在其中某个RadioGroup被选中时,清除另一个RadioGroup的选中状态。实现如下:

XML:




    

    

        

        

    

    

        

        

    


Java:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;

/**
 * Created by xuhongchuan on 16/4/30.
 */
public class PriceActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{

    private RadioGroup mRg1;
    private RadioGroup mRg2;

    private RadioButton mRb1;
    private RadioButton mRb2;
    private RadioButton mRb3;
    private RadioButton mRb4;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_price);
        initView();
    }

    private void initView() {
        mRg1 = (RadioGroup) findViewById(R.id.rg1);
        mRg2 = (RadioGroup) findViewById(R.id.rg2);

        mRb1 = (RadioButton) findViewById(R.id.rb1);
        mRb2 = (RadioButton) findViewById(R.id.rb2);
        mRb3 = (RadioButton) findViewById(R.id.rb3);
        mRb4 = (RadioButton) findViewById(R.id.rb4);

        mRb1.setOnCheckedChangeListener(this);
        mRb2.setOnCheckedChangeListener(this);
        mRb3.setOnCheckedChangeListener(this);
        mRb4.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.rb1:
                mRg2.clearCheck();
                break;
            case R.id.rb2:
                mRg2.clearCheck();
                break;
            case R.id.rb3:
                mRg1.clearCheck();
                break;
            case R.id.rb4:
                mRg1.clearCheck();
                break;
            default:
                break;
        }
    }
}

你可能感兴趣的:(Android RadioButton实现多行布局)