我正在尝试在片段而不是活动中使用RadioGroup小部件。我在以下代码行中遇到错误:
RadioButton button = new RadioButton(this);
我不确定要传递什么,而不是“ this”
我认为问题出在上面的摘录中或此处:
RadioGroup group = (RadioGroup) getView().findViewById(R.id.radioGroup);
完整代码:
public class fragment1 extends Fragment {
private Button btnNextFrag;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
createRadioButtons();
return view;
}
private void createRadioButtons() {
RadioGroup group = (RadioGroup) getView().findViewById(R.id.radioGroup);
String[] questions1 = getResources().getStringArray(R.array.question_1_answers);
for (int i=0;i<questions1.length;i++){
String question = questions1[i];
RadioButton button = new RadioButton(this);
button.setText(question);
group.addView(button);
}
}
}
答案 0 :(得分:1)
构造函数需要上下文,因此请使用getActivity()
而不是this
。您也可以使用getContext()
。
答案 1 :(得分:0)
public class fragment1 extends Fragment {
private Button btnNextFrag;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
createRadioButton(view);
return view;
}
private void createRadioButton(View view) {
RadioGroup group = (RadioGroup)view.findViewById(R.id.radioGroup);
String[] questions1 = getResources().getStringArray(R.array.question_1_answers);
for (int i=0;i<questions1.length;i++){
String question = questions1[i];
RadioButton button = new RadioButton(getActivity());
button.setText(question);
group.addView(button);
}
}
}