gpt4 book ai didi

android-studio - 如何在另一个 Activity 中使用一个 Activity 的 onActivityForResult

转载 作者:行者123 更新时间:2023-12-02 13:37:01 24 4
gpt4 key购买 nike

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

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

选择器 Activity :

    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?
}

选择适配器:
    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 的方法。

最佳答案

你必须开始ChooserActivitystartActivityForResult()来自 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(...)MainActivity并处理结果

关于android-studio - 如何在另一个 Activity 中使用一个 Activity 的 onActivityForResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54023688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com