我不知道我是否正確地得到了您的問題,但我猜您的主要活動正在調用具有ListView的活動,然後您希望返回主活動中的結果,對嗎?
如果是這樣,你顯示的代碼是不正確的做你想做的事。您正在尋找的是在您的主要活動中使用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();
}
下面是我的主要活動調用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.
}
你將不得不重寫onActivityResult
在MainActivity像這樣的東西:
@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官方文檔中的this link,他們在那裏有很多有用的東西。
我希望這可以幫助你。
在接收器的工作
@set結果得到的數據發送的意圖正確? –
我忘了在主要活動中提到有編輯文本,我需要它,所以如果你去到列表視圖並回來填充的編輯文本仍然保持填充 –
編號setResult只是在意圖設置一個變量說這項活動完成了預期的工作,並且收集到了結果。這裏的訣竅是,您使用startActivityForResult啓動了List活動,這意味着當您返回MainActivity時,要執行的第一個方法將是onActivityResult,其中數據變量是您在myList(send)上創建的意圖,resultCode是你在setRestult中設置。 –