我試過這個代碼..當模擬器啓動時,它將在單行中顯示三個單選按鈕。但我需要一個按鈕事件。即;如果我點擊按鈕,它應該詢問單選按鈕的數量。那麼如果我給出計數,它必須根據給定的計數顯示單選按鈕。例如,如果我將計數設置爲3,則它必須在單行中顯示三個單選按鈕。 非常感謝您的幫助。 在此先感謝。如何按給定數量的計數動態添加單選按鈕?
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
for(int row=0; row < 1; row++)
{
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for(int i = 1; i < 4; i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId((row * 2) + i);
rdbtn.setText("Radio " + rdbtn.getId());
ll.addView(rdbtn);
}
((ViewGroup)findViewById(R.id.radiogroup)).addView(ll);
}
}
}
這是XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<RadioGroup
android:id="@+id/radiogroup"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
非常感謝你..它工作正常! –
以防萬一有人在同一個問題上絆倒: 我試過這個解決方案,但是顯示的層次結構(radiogroup-> linearlayout-> radiobutton)我沒有得到檢查的單選按鈕:((RadioGroup)findViewById(R.id .radiogroup))getCheckedRadioButtonId(); 我需要切換線性佈局,以便將radiobutton直接添加到radiogroup中(如linearlayout-> radiogroup-> radiobutton)。 –
這工作正常,但允許在同一時間檢查多個單選按鈕!爲防止出現這種情況,只需將單選按鈕添加到線性佈局,直接添加到單選按鈕的組。 –