我不确定我是否正确解决了您的问题,但我猜您的 Main 活动正在调用具有 ListView 的活动,然后您希望将结果返回到 Main 活动中,对吗?
如果是这样,您显示的代码不是做您想做的事情的正确方法。您正在寻找的是在您的主要活动中使用StartActivityForResult
和覆盖该方法。onActivityResult
我不确切知道如何使用 Monodroid 和 C#,但我可以给你一个 Java 示例,我相信它会帮助你理解如何获得你想要的东西:
假设我的 ListView 活动称为myList并扩展了 ListActivity ,我的主要活动称为MainActivity。下面是 myList 的 OnListItemClick方法:
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
String text = String.valueOf(labels[position]);
// Create the intent with the extras
Intent send = new Intent();
send.putExtra("text_from_list", text);
// Set the result to OK (meaning the extras are put as expected by the caller)
setResult(RESULT_OK, send);
// you need this so the caller (MainActivity) knows that the user completed
// this activity (myList) as expected (clicking on the item to return a result)
// and didn't just leave the activity (back button)
// Close this List Activity
finish();
}
下面是我的Main Activity中调用 myList 的方法:
private void callListActivity(){
Intent call = new Intent(MainActivity.this, myList.class);
startActivityForResult(call, 1);
// The second field is just a number to identify which activity
// returned a result when a result is received (you can have
// several calls to different activities expecting results from
// each one of them). This number is called requestCode.
}
您将不得不使用以下内容覆盖MainActivityonActivityResult
中的 :
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check if the returned data came from myList (requestCode 1) and if
// data was actually received (check if resultCode = RESULT_OK)
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String text = data.getStringExtra("text_from_list");
// you have to use the same string identifier you used
// when you put the extra in the Intent in myList
TextView tvYearChange = (TextView)findViewById(R.id.tvYearchange);
tvYearChange.setText(text);
}
else {
// Do something if the Activity didn't return data
// (resultCode != RESULT_OK)
}
}
// If you are expecting results from other Activities put more if
// clauses here with the appropriate request code, for example:
// if (requestCode == 2) {
// DoSomething;
// }
// And so on...
}
将此 Java 代码修改为可与 Monodroid 一起使用的 C# 代码应该不难。另外,看看Android 官方文档中的这个链接,那里有很多有用的东西。
我希望这可以帮助你。