Basic Android Training: Using RadioButton and RadioGroup Example
Create
android project MyFeelingApp.
Then copy
the following files:
|
<?xml version="1.0"
encoding="utf-8"?>
<resources>
<string name="app_name">My Feeling App</string>
<string name="hello">Hello World,
MyFeelingAppActivity!</string>
<string name="instruction">How are you?</string>
<string name="radioStressLbl">Stress</string>
<string name="radioHappyLbl">Happy</string>
</resources>
|
|
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/instruction"
/>
<RadioGroup
android:id="@+id/radioFeelings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<RadioButton
android:id="@+id/radioStress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radioStressLbl" />
<RadioButton
android:id="@+id/radioHappy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radioHappyLbl" />
</RadioGroup>
</LinearLayout>
|
|
package com.kent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MyFeelingAppActivity extends Activity
implements RadioButton.OnClickListener{
private RadioGroup radioFeelings;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((RadioButton)findViewById(R.id.radioStress)).setOnClickListener(this);
((RadioButton)findViewById(R.id.radioHappy)).setOnClickListener(this);
}
public void onClick(View v) {
radioFeelings = (RadioGroup) findViewById(R.id.radioFeelings);
// Get selected option ID from RadioGroup
int iSelectedID = radioFeelings.getCheckedRadioButtonId();
// Return the RadioButton object with selected ID
RadioButton
radioFeeling = (RadioButton) findViewById(iSelectedID);
Toast.makeText(MyFeelingAppActivity.this,
radioFeeling.getText().toString(),
Toast.LENGTH_SHORT).show();
}
}
|
No comments:
Post a Comment