RadioGroup & RadioButton (建立多選1的button及動態)
//建立多選1的button
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<RadioGroup
android:id="@+id/rdbGp1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/rdb1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_launcher"
android:text="Option 1"/>
<RadioButton
android:id="@+id/rdb2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_launcher"
android:text="Option
21"/>
</RadioGroup>
</LinearLayout>
//建立多選1的button動態
//建立多選1的button動態
public class RadioActivity extends Activity {
@Override
protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
if
(savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container,
new PlaceholderFragment()).commit();
}
}
@Override
public boolean
onCreateOptionsMenu(Menu menu) {
// Inflate the
menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.radio,
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);
}
/**
* A placeholder fragment containing a simple
view.
*/
public static class
PlaceholderFragment extends Fragment {
private View
rootView;
public
PlaceholderFragment() {
}
@Override
public View
onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle
savedInstanceState) {
rootView =
inflater.inflate(R.layout.fragment_radio,
container,
false);
RadioGroup
radioGroup=(RadioGroup)rootView.findViewById(R.id.rdbGp1);
radioGroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
@Override
public
void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton
rb1=(RadioButton)rootView.findViewById(R.id.rdb1);
if(rb1.isChecked()){
Toast.makeText(PlaceholderFragment.this.getActivity(),
"Option
1 checked!",
Toast.LENGTH_SHORT)
.show();
}else{
Toast.makeText(PlaceholderFragment.this.getActivity(),
"Option
2 checked!",
Toast.LENGTH_SHORT)
.show();
}
}
});
return
rootView;
}
}
}
沒有留言:
張貼留言