2016-12-26 144 views
1

我有一個導航活動由碎片組成,並且我有一個連接到onClickListener的按鈕,該按鈕運行onClick方法。該應用程序正常打開也是如此的片段,但每當我按一下按鈕,應用程序崩潰添加getCheckedRadioButtonId()時應用程序崩潰

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進入一個單選按鈕

int selectedId = radioGroup.getCheckedRadioButtonId(); 

沒有這一行,打開應用程序和片段正常,單擊該按鈕時,應用程序不會崩潰,我加了一個烤麪包和它沒有上面的代碼行工作正常。任何人都可以解釋如何解決此問題?謝謝

回答

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; 
} 
+0

謝謝你,工作 – Taha

+0

你的歡迎,快樂編碼 –

1

找到你RadioGroup考慮不被點擊,但在片段的根認爲,所以這行:

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

更改爲此:

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

希望它可以幫助...

+0

這是個好主意,但它並沒有OnClick方法裏面工作,快速的學習能力說把那個在onCreateView方法行,工作 – Taha

相關問題