我目前正在为github项目添加更多功能供个人使用。我需要通过以下任一方式创建要在网格 View 中显示的应用程序列表:
1.自己写程序包名称(此功能已存在)或
2.从应用程序列表中选择(我要实现的目标)-使用ChooserAdapter在ChooserActivity中实现所有功能。
解决我的问题的方法是将信息传递给MainActivity并调用其onActivityResult方法,因为有很多事情我无法复制粘贴。
对于(每个网格 View 项目的)clickclick,我在ChooserAdapter中创建了OnItemClickListener接口(interface),并在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的方法。
最佳答案
您必须以ChooserActivity
中的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(...)
中的MainActivity
并处理结果