我想通过使用 startActivityForResult() 方法为结果启动Activity。现在启动的 Activity 有一个带有适配器类的 ListView 。我已经编写了以下 ListView 适配器,因此当用户选择任何项目时,它应该返回到调用 Activity 具有所选项目名称。我无法调用 2 个方法
setResult() and finish() in following code
适配器代码:
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SharedPreferences prefernces = mContext.getSharedPreferences("MyKey111", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = prefernces.edit();
editor1.putString("Custname",customerpopulationlist.get(position).getName());
editor1.putString("let_id", customerpopulationlist.get(position).getLetId());
editor1.commit();
Intent intentMessage = new Intent();
// put the message in Intent
intentMessage.putExtra("MESSAGE", "hello");
intentMessage.putExtra("selected_refer", customerpopulationlist.get(position).getLetId());
setResult(RESULT_OK, intentMessage);
finish();
}
});
最佳答案
您必须保留对创建适配器的 Activity 的引用,然后将结果设置为该 Activity 。您正在做的事情是设置 OnClickListener 对象的结果!!
将 Activity 对象添加到适配器构造函数中,并将其保存在适配器的本地变量中,并调用它 act,然后调用 activtiy 的 setResult() ,如下所示:
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SharedPreferences prefernces = mContext.getSharedPreferences("MyKey111", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = prefernces.edit();
editor1.putString("Custname",customerpopulationlist.get(position).getName());
editor1.putString("let_id", customerpopulationlist.get(position).getLetId());
editor1.commit();
Intent intentMessage = new Intent();
// put the message in Intent
intentMessage.putExtra("MESSAGE", "hello");
intentMessage.putExtra("selected_refer", customerpopulationlist.get(position).getLetId());
//THESE TWO LINES NEED TO BE CHANGED
act.setResult(RESULT_OK, intentMessage);
act.finish();
}
});
关于android - ListView 适配器 setResult() 和 Finish() 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39943058/