package iamshiao.sample;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CustomizedDialog extends Activity {
//客製化視窗「搜尋」。
private View customerViewSearch;
protected AlertDialog dialogSearch;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//客製化視窗「搜尋」,產生。
LayoutInflater factory = LayoutInflater.from(this);
customerViewSearch = factory.inflate(R.layout.dialog_search,null);
dialogSearch = new AlertDialog.Builder(this).create();
dialogSearch.setView(customerViewSearch);
//設定 客製化視窗「搜尋」內按鈕觸發事件。
((Button)customerViewSearch.findViewById(R.id.Button_search))
.setOnClickListener(
new OnClickListener(){
@Override
public void onClick(View v) {
//取得文字方塊中的關鍵字字串
String searchKey = ((EditText)customerViewSearch.findViewById(
R.id.EditText_search)).getText().toString();
//結束dialog
dialogSearch.dismiss();
Toast.makeText(CustomizedDialog.this,
"搜尋的內容為:" + searchKey, Toast.LENGTH_SHORT).show();
}
}
);
//設定使用倒回鍵會結束dialog
dialogSearch.setOnKeyListener(new OnKeyListener(){
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if(KeyEvent.KEYCODE_BACK==keyCode)
dialogSearch.dismiss();
return false;
}
});
//顯示dialog
dialogSearch.show();
}
}
程式開啟時將會直接show出搜尋視窗,按下搜尋後會用Toast展示取得的搜尋字串。首先先宣告客製化視窗View的customerViewSearch,還有實際的AlertDialog物件dialogSearch。 完成宣告後利用LayoutInflater做customerViewSearch的layout xml指定,再接著建構dialogSearch的實體並把view指定給它。
第二步,利用customerViewSearch的findViewById方法找出view中的搜尋鈕並指定按下事件發生後展示Toast。
為了防止使用倒回鍵可能發生的非預期錯誤,在dialog上設置倒回鍵的監聽,如果有觸發倒回,就關閉搜尋視窗。
最後使用show方法將dialog置於畫面前景。
完整範例下載

沒有留言:
張貼留言