2011年5月29日星期日

利用 AlertDialog.Builder 創建包含編輯文本視圖 (EditText) 的對話框

包含編輯文本視圖 (EditText) 的對話框


package com.AndroidEditDialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidEditDialog extends Activity {

Button btnEdit;
TextView textOut;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnEdit = (Button)findViewById(R.id.edit);
textOut = (TextView)findViewById(R.id.textout);

btnEdit.setOnClickListener(btnEditOnClickListener);
}

private Button.OnClickListener btnEditOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

AlertDialog.Builder editDialog = new AlertDialog.Builder(AndroidEditDialog.this);
editDialog.setTitle("--- Edit ---");

final EditText editText = new EditText(AndroidEditDialog.this);
editText.setText(textOut.getText());
editDialog.setView(editText);

editDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
textOut.setText(editText.getText().toString());
}
});
editDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
//...
}
});
editDialog.show();

}};
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Edit"
/>
<TextView
android:id="@+id/textout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You can change it"
/>
</LinearLayout>

沒有留言:

發佈留言