我有導航活動由碎片組成。目前,該應用程序可以從radiogroup中選取所選的ID,並通過單擊按鈕將其文本顯示爲敬酒。但應用程序只顯示已檢查的單選按鈕(定義爲xml),如果我更改所選的單選按鈕,它仍將顯示按xml中的定義進行檢查的那個按鈕。這是java類( FirstFragment.java)單選按鈕的更改未註冊
public class FirstFragment extends Fragment implements View.OnClickListener {
View myView;
private RadioGroup radioGroup;
private RadioButton radioButton;
Button btnDisplay;
String text;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.first_layout, container, false);
btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(this);
radioGroup = (RadioGroup) myView.findViewById(R.id.radio);
int selectedId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) myView.findViewById(selectedId);
return myView;
}
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),
text = radioButton.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
這是XML文件
<RadioGroup
android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="89dp">
<RadioButton
android:id="@+id/radioGram"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:text="Gram"/>
<RadioButton
android:id="@+id/radioKilogram"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kilogram"
android:textSize="16sp"
android:checked="true"/>
</RadioGroup>
因此,在這種情況下,麪包會顯示「公斤」,但如果我檢查「革蘭氏陰性」單選按鈕,麪包仍然會顯示「千克」。有誰能幫助解決這個問題嗎謝謝
這兩項碰撞代碼段的應用程序,我想通一件事出來,那就是線,如「RadioGroup中radioGroup中=(RadioGroup中)findViewById(R.id.yourRadioGroup); 「或」rb_1 =(RadioButton)myView.findViewById(R.id.radioGram);「當按鈕被點擊時崩潰應用程序 – Taha
還有什麼我可以嘗試? – Taha
@Taha檢查編輯後的替代方式答案...也請確保您的佈局ID和單選按鈕ID是正確的.. – rafsanahmad007