我有一個選項卡式活動,在其中一個片段中,我有一個帶有3個單選按鈕的無線電組。我想弄清楚如何確定選擇哪個單選按鈕。我懷疑我需要爲這個片段創建一個java文件。不過,我不確定這是否正確。我跟着一個java文件的例子。我修改它,它不工作。當我點擊一個單選按鈕時沒有任何反應。在標籤片段中使用單選按鈕
fragment_calories_want.xml(省略代碼的問題不相關)
<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="layout.CaloriesWant">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="100px"
android:id="@+id/radioGroup"
android:orientation="horizontal"
android:layout_marginTop="82dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<RadioButton
android:text="Grams"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButtonGrams"
android:layout_weight="1"
tools:text="Grams" />
<RadioButton
android:text="Ounces"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButtonOunces"
android:layout_weight="1" />
<RadioButton
android:text="Pounds"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButtonPounds" />
</RadioGroup>
</RelativeLayout>
CaloriesWantFragment.java
package com.example.crims.caloriecalculator;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class CaloriesWantFragment extends Fragment {
private RadioButton radioButton1;
private RadioButton radioButton2;
private RadioButton radioButton3;
private RadioGroup radioGroupOne;
String buttonSelected;
Activity activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_calories_want, container, false);
radioButton1 = (RadioButton) view.findViewById(R.id.radioButtonGrams);
radioButton2 = (RadioButton) view.findViewById(R.id.radioButtonOunces);
radioButton3 = (RadioButton) view.findViewById(R.id.radioButtonPounds);
radioGroupOne = (RadioGroup) view.findViewById(R.id.radioGroup);
radioGroupOne.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch(i){
case R.id.radioButtonGrams:
buttonSelected = "button one selected";
break;
case R.id.radioButtonOunces:
buttonSelected = "button two selected";
break;
case R.id.radioButtonPounds:
buttonSelected = "button three selected";
break;
default:
}
Toast.makeText(activity, "radio button selected " + buttonSelected, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
如果你寫的radioGroup中一行findViewById? –
你可以使用'radioGroup.getCheckedRadioButtonId();'來獲得選定的單選按鈕ID –
@RishabhMahatha我剛剛添加它。文件已更新,並仍有相同的問題。當我點擊一個按鈕時,期待烤麪包可以顯示某些東西。 – crims