添加getCheckedRadioButtonId()时应用崩溃

时间:2016-12-26 08:22:46

标签: android android-studio android-fragments

我有一个由片段组成的导航活动,我有一个附加到onClickListener的按钮,它运行onClick方法。应用程序正常打开,片段也是如此,但每当我点击按钮时,应用程序崩溃

public class FirstFragment extends Fragment implements View.OnClickListener {

View myView;

private RadioGroup radioGroup;
private Button btnDisplay;


@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);
    return myView;
}

@Override
public void onClick(View v) {
    radioGroup = (RadioGroup) v.findViewById(R.id.radio);

    int selectedId = radioGroup.getCheckedRadioButtonId();
    }
}

通过一些测试,我发现这条线路造成了问题。我需要这一行,因为我想将selectedId传递给radiobutton

int selectedId = radioGroup.getCheckedRadioButtonId();

如果没有这一行,应用程序和片段会正常打开,单击按钮时应用程序不会崩溃,我添加了一个toast,并且没有上面的代码行就可以正常工作。有谁能解释如何解决这个问题?谢谢

2 个答案:

答案 0 :(得分:1)

将此行放在onCreateview

radioGroup = (RadioGroup) v.findViewById(R.id.radio);

喜欢这个

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View myView = inflater.inflate(R.layout.first_layout, container, false);
     radioGroup = (RadioGroup) myView .findViewById(R.id.radio);
    btnDisplay = (Button) myView.findViewById(R.id.btnDisplay);
    btnDisplay.setOnClickListener(this);
    return myView;
}

答案 1 :(得分:1)

找不到您点击的RadioGroup视图但是在片段的根视图中,所以这一行:

radioGroup = (RadioGroup) v.findViewById(R.id.radio);

改为:

radioGroup = (RadioGroup) myView.findViewById(R.id.radio);
希望它有所帮助...