onActivityResult没有从片段调用

时间:2014-11-17 10:15:34

标签: android android-activity android-fragments onactivityresult

我有这个片段,它使用start活动调用结果。这个活动应该显示一个锁定模式。问题是永远不会调用'onActivityResult'。我把一些烤面包检查,但它永远不会打印出来。

    public class int_Create_Pattern extends Fragment {
    private static final int REQ_CREATE_PATTERN = 1;

    @Override
    public void onStart() {
        // TODO Auto-generated method stub

        super.onStart();
        LockPatternView.MATRIX_WIDTH = 4;
        Intent intent = new Intent(LockPatternActivity.ACTION_CREATE_PATTERN,
                null, getActivity().getBaseContext(), LockPatternActivity.class);
        startActivityForResult(intent, REQ_CREATE_PATTERN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(resultCode, resultCode, data);

        switch (requestCode) {
        case REQ_CREATE_PATTERN: {
            if (resultCode == LockPatternActivity.RESULT_OK) {
                char[] pattern = data
                        .getCharArrayExtra(LockPatternActivity.EXTRA_PATTERN);
                DataBaseHandler handler = new DataBaseHandler(getActivity()
                        .getApplicationContext());
                handler.open();

                String PatternToWrite = new String(pattern);
                handler.createPattern(PatternToWrite);
                handler.close();
                Log.d("DEBUG", new String(pattern));

                Toast.makeText(getActivity().getApplicationContext(),
                        "Pattern Recorded", Toast.LENGTH_LONG).show();

            }
            if (resultCode == LockPatternActivity.RESULT_CANCELED) {

                Toast.makeText(getActivity().getApplicationContext(),
                        "Pattern Cancelled", Toast.LENGTH_LONG).show();
            }
            break;
        }// REQ_CREATE_PATTERN

        }

    }

   }

2 个答案:

答案 0 :(得分:0)

onActivityResult应该是一个Activity方法,而不是片段。 另一个问题是你不应该从片段中调用新的活动。实现用于通信的接口,如下面的链接

所述

http://developer.android.com/training/basics/fragments/communicating.html

保存片段的活动应该负责调用新活动并处理结果。

答案 1 :(得分:0)

In Parent Class: do this code

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.dualPane);
    fragment.onActivityResult(requestCode, resultCode, data);
} 
In Child Class:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   //in fragment class callback 
}