第七課 RadioGroup和RadioButton的用法


1.RadioButton一般都是分組使用,即先創建一個組RadioGroup(是一個方框),然后將RadioButton在方框中排列,那么方框中的RadioButton就屬於同一個組,同時要給RadioGroup添加一個ID.在以后的控制中只需給這個組添加一個監聽器即可。

2.如何給組添加監聽器,並找出是組中的哪一個成員按下

public class MainActivity extends AppCompatActivity {
    TextView tx;
    RadioGroup G_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tx = (TextView)findViewById(R.id.textView2);
        G_name = (RadioGroup)findViewById(R.id.RadioGroup1);
       //創建並實現監聽器(此處和之前創建的監聽器方法不同,這一次在創建的時候就實現監聽整個過程都是在onCreate中完成)
        G_name.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //獲取變更后的選中項的ID
                int radioButtonId = arg0.getCheckedRadioButtonId();//獲得按下單選框的ID,並保存在radioButtonId
                //根據ID獲取RadioButton的實例
                RadioButton rb = (RadioButton)findViewById(radioButtonId);//根據ID將RB和單選框綁定在一起
                //更新文本內容,以符合選中項
                tx.setText("您的名字是:" + rb.getText());//獲取單選框的文字,並在TextView中顯示
            }
        });//監聽器到此結束

     //   ImageSpan span = new ImageSpan(this, R.mipmap.xiaogou);
      //  SpannableString spanStr = new SpannableString("我是小狗 ");
       // spanStr.setSpan(span, spanStr.length()-1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
      //  tx.setText(spanStr);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM