Android基础控件之单选框(RadioButton)

要完成单选框显示,我们需要使用到RadioGroup和RadioButton(单选框),

RadioGroup用于对单选框进行分组,相同组内的单选框只有一个单选框能被选中。(例子代码请见下方备注栏) 

RadioGroup.check(R.id.dotNet);将id名为dotNet的单选框设置成选中状态。

(RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());//获取被选中的单选框。

调用setOnCheckedChangeListener()方法,处理单选框被选择事件,把RadioGroup.OnCheckedChangeListener实例作为参数传入  
界面设计

 
 
 
 
     
     
 
 
处理程序: 
public void onCreate(Bundle savedInstanceState) { 
       ...... 
        RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);  
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
            public void onCheckedChanged(RadioGroup group, int checkedId) { 
                RadioButton radioButton = (RadioButton) findViewById(checkedId); 
                Log.i(TAG, String.valueOf(radioButton.getText())); 
            } 
        }); 
}

另外附上一例:

private RadioButton homeBtn,catagoryBtn,carBtn,moreBtn,buyBtn;
		homeBtn = (RadioButton)findViewById(R.id.main_tab_home);
		catagoryBtn = (RadioButton)findViewById(R.id.main_tab_catagory);
		carBtn = (RadioButton)findViewById(R.id.main_tab_car);
		buyBtn = (RadioButton)findViewById(R.id.main_tab_buy);
		moreBtn = (RadioButton)findViewById(R.id.main_tab_more);
		
		OnClickListener handle =  new OnClickListener(){
			public void onClick(View v){
				switch(v.getId()){
				case R.id.main_tab_home:
					tabHost.setCurrentTabByTag("home");
					break;
				case R.id.main_tab_catagory:
					tabHost.setCurrentTabByTag("catagory");
					break;
				case R.id.main_tab_car:
					tabHost.setCurrentTabByTag("car");
					break;
				case R.id.main_tab_buy:
					tabHost.setCurrentTabByTag("buy");
					break;
				case R.id.main_tab_more:
					tabHost.setCurrentTabByTag("more");
					break;
				}
					
			}
		};
		
		homeBtn.setOnClickListener(handle);
		catagoryBtn.setOnClickListener(handle);
		carBtn.setOnClickListener(handle);
		buyBtn.setOnClickListener(handle);
		moreBtn.setOnClickListener(handle);



	        
	        
	        
	        
	        
	    


你可能感兴趣的:(android,JAVA)