2013-08-02 23 views
0

我正在尝试在我的SherlockFragment活动中实现无线电组....我无法做到这一点。当我运行应用程序时,出现“java.lang.NullPointer”异常并且屏幕上不显示任何活动。如何在Android Fragment活动中使用Radio Groups

这里是我的代码

public class Fragment_1 extends SherlockFragment { 

RadioGroup cls; 



    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 





    final View V= inflater.inflate(R.layout.fragment_1, container, false); 




cls= (RadioGroup) V.findViewById(R.id.radioclass); 
cls.clearCheck(); 


OnClickListener listener = new OnClickListener(){ 

/@Override 
public void onClick(View V) { 
    // TODO Auto-generated method stub 

    RadioButton rb = (RadioButton) V; 


    clss=rb.getText().toString(); 

} 

}; 
RadioButton rb1 = (RadioButton)V. findViewById(R.id.radioButton1); 
rb1.setOnClickListener(listener); 

RadioButton rb2 = (RadioButton)V. findViewById(R.id.radioButton2); 
rb2.setOnClickListener(listener); 
rb2.setChecked(true); 





return V; 
} 

} 
+0

我不明白你的片段的结构。 onCreate/onActivityCreated在哪里?我期望看到你的代码片段生命周期方法。如果您认为程序的结构是有效的,那么从一个简单的示例开始,并发布logcat。 – IanB

+0

我已更新我的代码。编译程序时没有错误,但是当我运行我的应用程序时,这个片段不显示,整个应用程序停止。什么是正确的方法来做到这一点? – user2647003

回答

0

我不认为我会通过发布剪切和粘贴的解决方案做你任何好处,但是这可能是有益的 (不,如果你太惊讶找到一些错误):

public class Fragment_1 extends SherlockFragment { 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { 
     // inflate ... 
     View view = inflater.inflate(R.layout.fragment_1, container, false); 
     return view; 
    } 

    public void onActivityCreated (Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 


     Button rb1 = (Button) getActivity().findViewById(R.id.radioButton1); 
      //then do other buttons ... 

     rb1.setOnClickListener(next_Listener); 
      //then do other buttons ... 


    } 

    private OnClickListener next_Listener = new OnClickListener() { 
     public void onClick(View v) { 

     //xml find out which radio button has been checked ... 
     RadioGroup radio_grp=(RadioGroup)getActivity().findViewById(R.id.radio_grp); //change or leave out this line (I've put it in because you might find it useful later) 
      RadioButton rb1=(RadioButton)getActivity().findViewById(R.id.radioButton1); //you dont need to do this again if global ... 
      if(rb1.isChecked() == true) { 
       //toast ... button has been selected ... 
      } 
     } 
    } 

} 
相关问题