【问题标题】:Passing context for a radio group in a fragment instead of activity?在片段而不是活动中传递无线电组的上下文?
【发布时间】:2018-12-29 06:32:46
【问题描述】:

我正在尝试在片段而不是活动中使用 RadioGroup 小部件。以下代码行出现错误:

RadioButton button = new RadioButton(this);

我不确定要传递什么而不是“this”

我相信问题出在上面的 sn-p 或这里:

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);
    }
 }
}

【问题讨论】:

    标签: android-studio android-fragments radio-group


    【解决方案1】:

    构造函数需要上下文,所以使用getActivity() 而不是this。你也可以使用getContext()

    【讨论】:

    • 我试过这个拳头,但虽然我没有收到错误,但我的应用程序在尝试加载片段时崩溃...
    • 您应该从 logcat 发布堆栈跟踪。
    【解决方案2】:
    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);
        }
    }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多