2

我製作演示應用程序FragmentActivity之間的兩個片段,如一個是正常擴展片段,二是擴展DialogFragment。如何在android中的兩個片段之間訪問onActivityResult()方法?

我不會在第一個片段中的onActivityResult()方法中處理,因爲第一個片段打開對話框片段確定按下然後訪問該方法。

請幫我 感謝提前

第一塊碎片代碼,

public class MyListFragment extends Fragment { 

    View mView; 
    protected static final int REQ_CODE = 1010; 

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

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == Activity.RESULT_OK) { 
      if (requestCode == REQ_CODE) { 
       // Access here 
      } 
     } 
     super.onActivityResult(requestCode, resultCode, data); 
    } 
} 

回答

4

我找到答案MYSELF

這是我如何處理片段和對話片段,

之間的通信

MyListFragment Code,

public class MyListFragment extends Fragment { 

    View mView; 
    protected static final int REQ_CODE = 1010; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     mView = inflater.inflate(R.layout.list_fragment, container, false); 

     Button mButton = (Button) mView.findViewById(R.id.button); 
     mButton.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       MyDialogFragment dialog = new MyDialogFragment(); 
       dialog.setTargetFragment(MyListFragment.this, REQ_CODE); 
       dialog.show(getFragmentManager(), "dialog"); 
      } 
     }); 

     return view; 
    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == Activity.RESULT_OK) { 
      if (requestCode == REQ_CODE) { 
       // Access here 
       Log.i(TAG, "onActivityResult Access here method"); 
      } 
     } 
     super.onActivityResult(requestCode, resultCode, data); 
    } 
} 

DialogFragment代碼,

public class MyDialogFragment extends DialogFragment { 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) { 

     AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
     builder.setMessage("My dialog message") 
     .setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       notifyToTarget(Activity.RESULT_OK); 
      } 
     }) 
     .setNegativeButton("Cancel", 
       new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       notifyToTarget(Activity.RESULT_CANCELED); 
      } 
     }); 
     return builder.create(); 
    } 

    private void notifyToTarget(int code) { 
     Fragment targetFragment = getTargetFragment(); 
     if (targetFragment != null) { 
      targetFragment.onActivityResult(getTargetRequestCode(), code, null); 
     } 
    } 
} 

此代碼我希望幫助我們。

相關問題