我想開發一些非常基本的代碼,使用startActivityForResult,我總是得到一個惱人的問題:從主要活動(只包含一個「你好單詞」editText)我打電話一個新的活動,其中只包含一個TextView,一個空的listView和一個ImageButton。當我點擊ImageButton時,它假設在我的mainActivity中意圖返回「ok」並將其打印到「hello word」editText中,但沒有任何反應。我已經閱讀了關於如何使用「StartActivity for result」的所有主題,但我沒有發現任何有用的信息。請幫助我。下面startActivityForResult Android
我的代碼是:
MainActivity
public class MainActivity extends AppCompatActivity {
TextView hw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hw = (TextView) findViewById(R.id.hw);
hw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),DeviceListActivity.class);
int resultCode = -1;
startActivityForResult(intent,resultCode);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
hw.setText(result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
DeviceListActivity:
public class DeviceListActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
final ImageButton nextBtn = (ImageButton) findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent returnIntent = new Intent();
String result = "Tout va bien!";
returnIntent.putExtra("result",result);
onActivityResult(1,1,returnIntent);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
嘗試http://www.javatpoint.com/android-startactivityforresult-example –
remove onActivityResult(1,1,returnIntent);從DeviceListActivity –
只需要2件事..從DeviceListActivity刪除** onActivityResult(1,1,returnIntent); **並將** int resultCode = -1; **與** int resultCode = 1; **在MainActivity –