0

我从片段访问活动的方法时遇到问题。或片段中的任何活动。

这是片段代码:

public class MainFragment extends Fragment {

private MainActivity ma = (MainActivity) getActivity();
public SipAudioCall call = null;
public SipManager mSipManager = null;
public SipProfile mSipProfile = null;



public MainFragment() {
    // TODO Auto-generated constructor stub

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Create a new TextView and set its text to the fragment's section
    // number argument value.
    LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.main_layout, container, false);

    final Button callbtn = (Button) mLinearLayout.findViewById(R.id.callbtn);
    final Button endbtn = (Button) mLinearLayout.findViewById(R.id.endbtn);



    callbtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            callbtn.setVisibility(View.GONE);
            endbtn.setVisibility(View.VISIBLE);
            ma.initiateCall();    
        }
    });

也许投射活动是错误的?提前谢谢

4

1 回答 1

1

我猜当你调用 getActivity() 时,片段没有附加到活动中。尝试在片段方法 onAttach() 中初始化活动引用。

所以是这样的:

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            ma = (MainActivity) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " Not MainActivity class instance");
        }
    }
于 2012-12-16T03:28:15.690 回答