創建一個對話主題活動以顯示當前活動。
public class TextEntryActivity extends Activity {
private EditText et;
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_entry);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
// title
try {
String s = getIntent().getExtras().getString("title");
if (s.length() > 0) {
this.setTitle(s);
}
} catch (Exception e) {
}
// value
try {
et = ((EditText) findViewById(R.id.txtValue));
et.setText(getIntent().getExtras().getString("value"));
} catch (Exception e) {
}
// button
((Button) findViewById(R.id.btnDone)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
executeDone();
}
});
}
/* (non-Javadoc)
* @see android.app.Activity#onBackPressed()
*/
@Override
public void onBackPressed() {
executeDone();
super.onBackPressed();
}
/**
*
*/
private void executeDone() {
Intent resultIntent = new Intent();
resultIntent.putExtra("value", TextEntryActivity.this.et.getText().toString());
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
啓動方式:
Intent foo = new Intent(this, TextEntryActivity.class);
foo.putExtra("value", "old value to edit");
this.startActivityForResult(foo, EDIT_ACTION);
然後捉對onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case EDIT_ACTION:
try {
String value = data.getStringExtra("value");
if (value != null && value.length() > 0) {
//do something with value
}
} catch (Exception e) {
}
break;
default:
break;
}
}
清單的響應被定義爲:
<activity
android:name=".utils.TextEntryActivity"
android:label="Type in the value"
android:theme="@android:style/Theme.Dialog" />
謝謝! 我希望解決方案不涉及意圖,但這是一個優雅的解決方案,因爲它是! 欣賞它,這解決了我的問題。 – Gus 2010-06-17 18:37:15
當我嘗試使用此代碼時,我得到'activity_text_entry無法解析或不是字段 txtValue無法解析或不是字段 btnDone無法解析或不是字段。 我錯過了什麼嗎? – 2011-09-16 13:44:30