Android开发——单选RadioGroup和复选CheckBox

  学习总是由简入深的,我们一起来看看单选RadioGroup和复选CheckBox的用法吧。

先附上一张效果图

Android开发——单选RadioGroup和复选CheckBox_第1张图片

XML代码



    
	    
	        
	        
	    
	
	
	    
	     
	     
	
	
我们前面已经对Android的XML代码有了一个简单的了解,我们上面的代码能够实现我们图里面的功能吗?大家一看就知道,其实并不能,所以呢我们看看下面这段Java代码。

package com.example.radiogroupAndCheckbox;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	
	private RadioButton rbMale=null;
	private RadioButton rbFemale=null;
	private CheckBox ckEat=null;
	private CheckBox ckSleep=null;
	private CheckBox ckPlaydd=null;
	private Button bt=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		rbMale=(RadioButton)findViewById(R.id.male);
		rbFemale=(RadioButton)findViewById(R.id.female);
		
		ckEat=(CheckBox)findViewById(R.id.eat);
		ckSleep=(CheckBox)findViewById(R.id.sleep);
		ckPlaydd=(CheckBox)findViewById(R.id.playdd);
		bt=(Button)findViewById(R.id.bt);
		bt.setOnClickListener(new SaveOnClickListener());
	}
	private class SaveOnClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String sex="";
			String fun="";String fun1="";String fun2="";String fun3="";
			String sInfo="";
			if (rbMale.isChecked()) {
				sex=rbMale.getText().toString();
			}
			if (rbFemale.isChecked()) {
				sex=rbFemale.getText().toString();
			}
			if (ckEat.isChecked()) {
				fun1=ckEat.getText().toString();
			}
			if(ckSleep.isChecked()){
				fun2=ckSleep.getText().toString();
			}
			if(ckSleep.isChecked()){
				fun3=ckPlaydd.getText().toString();
			}
			fun=fun1+" "+fun2+" "+fun3;
			sInfo="我是一个"+sex+"生,我想"+fun;
			Toast.makeText(getApplicationContext(), sInfo, Toast.LENGTH_LONG).show();
		}
		
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
这段代码我们不去看导的包,也不去看红色字体部分,这就是我们实现界面上单选复选以及提交显示功能效果的代码了。通过代码我们能很容易的理解,这段代码就是先找到我们XML里的View,然后为这些View的点击事件添加一个监听器,在点击button时后我们触发监听器,把结果通过Toast显示出来。

你可能感兴趣的:(Android)