如何在另一个活动中使用一个活动的onActivityForResult

时间:2019-01-03 13:54:18

标签: android-studio android-activity kotlin

我目前正在为github项目添加更多功能供个人使用。我需要通过以下任一方式创建要在网格视图中显示的应用程序列表:    1.自己写程序包名称(此功能已存在)或    2.从应用程序列表中选择(我要实现的目标)-使用ChooserAdapter在ChooserActivity中实现所有功能。

解决我的问题的方法是将信息传递给MainActivity并调用其onActivityResult方法,因为有很多事情我无法复制粘贴。     对于(每个网格视图项的)clickListener,我在ChooserAdapter中创建了OnItemClickListener接口,并在ChooserActivity中覆盖了它。

ChooserActivity:

    class ChooserActivity : BaseActivity(), ChooserAdapter.OnItemClickListener {
private val backButton: FloatingActionButton by bindView(R.id.back_button_2)

override fun onItemClick(app: ApplicationInfo?) {
    val intent = EditorActivity.IntentBuilder(context)
            .build()
    startActivityForResult(intent, 1)
}


public override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
    Toast.makeText(this, "onActivityResult called ...", Toast.LENGTH_SHORT).show()
    // !!!!!!
    MainActivity().onActivityResult(requestCode, resultCode, intent)
    //How can I write something similar to this to solve my problem?
}

ChooserAdapter:

    public class ChooserAdapter extends RecyclerView.Adapter<ChooserAdapter.ChooserHolder>{

private List<ApplicationInfo> listOfApps;
private Context mContext;
private PackageManager pm;
private OnItemClickListener listener;


public ChooserAdapter(@NonNull Context context, List<ApplicationInfo> list, OnItemClickListener l) {
    this.listOfApps = list;
    this.mContext = context;
    this.pm = context.getPackageManager();
    this.listener =
            new ChooserAdapter.OnItemClickListener(){
        @Override
        public void onItemClick(ApplicationInfo app){
            try{
                Intent intent = (new EditorActivity.IntentBuilder(mContext)).build();
                ((ChooserActivity)mContext).startActivityForResult(intent, 2);
            }catch (Exception e){
                Toast.makeText(mContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    };
}

public class ChooserHolder extends RecyclerView.ViewHolder{
     //stuff not useful to be shown
}}

以上代码的结果导致未使用所需的MainActivity()。onActivityResult(...),而是使用ChooserActivity的方法。

1 个答案:

答案 0 :(得分:1)

您必须从ChooserActivity的{​​{1}}开始startActivityForResult(),然后以这种方式传递结果MainActivity-> EditorActivity-> ChooserActivity

MainActivity

class ChooserActivity : BaseActivity(), ChooserAdapter.OnItemClickListener { .... public override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { Toast.makeText(this, "onActivityResult called ...", Toast.LENGTH_SHORT).show() setResult(Activity.RESULT_OK, intent) finish() } .... } 中覆盖onActivityResult(...)并处理结果