如何在Fragment中调用OnActivityResult以及它是如何工作的?

时间:2017-06-19 04:34:40

标签: android android-intent fragment onactivityresult

我想知道onActivityResult()是否可以在Fragment中使用,如果是,那么它是如何工作的,请举例说明。

8 个答案:

答案 0 :(得分:19)

你会打电话:

startActivityForResult(i, 1);

然后:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   //super.onActivityResult(requestCode, resultCode, data); comment this unless you want to pass your result to the activity.
}

答案 1 :(得分:3)

当然它会起作用,它会像活动一样工作。你有电话startActivityForResult(intent, requestCode); 通常会得到结果

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

答案 2 :(得分:2)

是的,你可以在Fragment.like这个

中使用OnActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
// perform your action here
}

现在你像这样调用onActivityResult

getActivity().startActivityForResult(). 

修改

以上答案陈旧

点击此处更新的答案https://stackoverflow.com/a/17085889/7666442

答案 3 :(得分:2)

在活动中使用此代码。

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag(childTag);
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, intent);
    }
}

答案 4 :(得分:1)

如果您在片段中调用startActivityForResult(),则结果将传递给父活动。

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);//will deliver result to desired fragment.
}
  

如何运作

如果您在活动中看到requestCode,它将像655545,现在

super.onActivityResult()将计算所需的片段和请求代码。

如果使用

找到ViewPager中所需片段索引的片段
requestCode>>16

requestCode&0xffff找到requestCode。

答案 5 :(得分:0)

In kotlin: - I can explain using two classes. if user go from one Activity to Another Activty and in back want data then this code help you

In class Abc
startActivityForResult(Intent(context, Bcd::class.java), 141)

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 141) {
            if (data!!.extras.get("add").equals("safal")) {
                Log.e("Print Name",data!!.extras.get("add"))
            }
        }
    }

In Class Bcd
 val intent = Intent()
 intent.putExtra("add", "safal")
 setResult(Activity.RESULT_OK, intent)

答案 6 :(得分:0)

您可以轻松在android studio 3.5中的Fragment中调用onActivityResult

,首先,应该有一个活动来获得结果。 OnActivity结果意味着必须在提示时提供结果视图。 现在,在上一个活动中,说

第一个是活动,另一个是第二个活动中的片段

首次活动的Xml代码可能如下:

     <RelativeLayout
     xmlns:androclass="http://schemas.android.com/apk/res/android"  
     xmlns:tools="http://schemas.android.com/tools"  
     android:layout_width="match_parent"  
     android:layout_height="match_parent"  
     tools:context=".MainActivity" >  
    <TextView  
    android:id="@+id/t1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignLeft="@+id/button1"  
    android:layout_alignParentTop="true"  
    android:layout_marginTop="48dp"  
    android:text="Default Message" />  
 <Button  
    android:id="@+id/b1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_below="@+id/textView1"  
    android:layout_centerHorizontal="true"  
    android:layout_marginTop="42dp"  
    android:text="GetMessage" />  
    </RelativeLayout>  

第二个XML代码将

     <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:paddingBottom="@dimen/activity_vertical_margin"  
   android:paddingLeft="@dimen/activity_horizontal_margin"  
   android:paddingRight="@dimen/activity_horizontal_margin"  
   android:paddingTop="@dimen/activity_vertical_margin"  
   tools:context=".SecondActivity" >  
<EditText  
    android:id="@+id/et1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignParentTop="true"  
    android:layout_marginTop="61dp"  
    android:layout_toRightOf="@+id/textView1"  
    android:ems="10" />  
<TextView  
    android:id="@+id/t1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_alignBaseline="@+id/editText1"  
    android:layout_alignBottom="@+id/editText1"  
    android:layout_alignParentLeft="true"  
    android:text="Enter Message:" />  
<Button  
    android:id="@+id/b1"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:layout_below="@+id/editText1"  
    android:layout_centerHorizontal="true"  
    android:layout_marginTop="34dp"  
    android:text="Submit" />  
  </RelativeLayout>  

现在,我们将添加startActivityForResult()方法和onActivityResult()方法

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

    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==2)
    {
        String message=data.getStringExtra("MESSAGE");
        if (message!=null){
            profileNameText.setText(message);
        }
      }
     }


     @Override
    public void onClick(View v) {
    Intent i ;
    switch (v.getId()){
        case R.id.profile_option_menu:
            Log.i("profileclicked","profile_menu_image_clicked()");
            PopupMenu popupMenu = new PopupMenu(getActivity(),v);
            MenuInflater inflater = popupMenu.getMenuInflater();
            inflater.inflate(R.menu.profile_menu,popupMenu.getMenu());
            popupMenu.show();
            popupMenu.setOnMenuItemClickListener(new 
            PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    Intent i;
                    switch (item.getItemId()) {

                            case R.id.edit_det:
                            i = new Intent(getActivity().getApplicationContext(), 
                            FirstActivity.class);
                            startActivityForResult(i, 2);
                            return true;
                        default:
                            return onOptionsItemSelected(item);
                    }
                }
            });
            break;
    }
}

第一个活动类的代码将是这样

        public class FirstActivity extends Activity {  
         EditText editText1;  
         Button button1;  
         @Override  
          protected void onCreate(Bundle savedInstanceState) {  
          super.onCreate(savedInstanceState);  
          setContentView(R.layout.activity_first);  
          editText1=(EditText)findViewById(R.id.et1);  
          button1=(Button)findViewById(R.id.b1);  
          button1.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View arg0) {  
                String message=editText1.getText().toString();  
                Intent intent=new Intent();  
                intent.putExtra("MESSAGE",message);  
                setResult(2,intent);  
                finish();//finishing activity  
             }  
         });  
       }  

这里我正在编写一个方法setResult(2,intent),其中2是结果代码,它将在第一个活动类的片段内进行检查,它将检查结果代码,如果条件满足,则它将更改内部的文本TextView。

答案 7 :(得分:0)

在 Kotlin 中,我们可以通过以下非常简单的方式完成此操作:

在 ExampleFragment.kt 中,让我们开始活动以拍摄图像。

private val REQUEST_CODE_GALLERY = 101

private fun openGallery() {
    val intent = Intent(Intent.ACTION_PICK)
    intent.type = "image/*"

    requireActivity().startActivityFromFragment(this, intent, REQUEST_CODE_GALLERY)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_GALLERY) {
        Log.d("TAG", "${data.toString()}")
    }
}

希望,这会有所帮助!