如何使Dialog像Activity一樣隨心所欲的使用?,dialogactivity
如何使Dialog像Activity一樣隨心所欲的使用?android中的Dialog像是寄生在Activity中,在彈出Dialog時,因受到系統風格定義,導致Dialog怎麼也不能如意,那麼今天就來探討下Dialog的使用。
要完全自訂一個Dialog,那麼就不要extends AlertDialog,我們在使用Activity時,先準備一個布局檔案xxx.xml,所有控制項大小都可以在布局檔案中寫好。其實Dialog也可以這麼做。
實現步驟: 1、準備好布局檔案: 2、組織布局中的控制項動作,寫成一個ViewHolder,我這裡寫的是TimeViewHolder,建構函式中要兩個參數:Context和View,這個 ViewHolder與Activity的ViewHolder不一樣,因為Activity是帶布局的,所以可以不要View這個參數。這個View可以看作是一個布局,所有的控制項都以它為載體
public TimeViewHolder(Context activity, View view) {
this.activity = activity;
this.root = view;
}
2、準備好一套風格:這個風格檔案定義在res/values/styles.xml中,當然可以寫到其他風格檔案中 < style name=
"picture_mode" parent =
"@android:Theme.Dialog" > < item name =
"android:windowFrame" >@null </ item> < item name =
"android:windowIsFloating" >true </ item> < item name =
"android:windowIsTranslucent" >false </ item> < item name =
"android:windowNoTitle" >true </ item> <!--除去title--> < item name =
"android:windowContentOverlay" >@null </ item> < item name =
"android:backgroundDimEnabled" >false </ item> < item name =
"android:windowBackground" >@null </ item> <!--除去背景色--> </style > 3、在Activity中建立Dialog: Dialog timeDialog =
new Dialog( mActivity , R.style.
picture_mode ) {//建立Dialog時,指定風格,帶一個Content參數:mActivity @Override
protected void onCreate(Bundle savedInstanceState) { //
TODO Auto-generated method stub
super .onCreate(savedInstanceState); setContentView(R.layout.
time );//在onCreate方法中,指定布局檔案,因上面指定了風格,所以這個 //Dialog的大小位置全都會因這個layout決定,所以你想怎樣就怎樣 View mView=getWindow().getDecorView();//關鍵在這裡,這個View,是你根據xml中的id來找對應控制項的。
if (timeViewHolder ==
null) { timeViewHolder =
new TimeViewHolder(mActivity , mView); }
}
@Override
protected void onStart() {//在這個方法中,你可以實現一些互動動作 //
TODO Auto-generated method stub
super .onStart();
Log.
i( "ytmfdw", "timeDialog onStart"); timeViewHolder .findViews(); }
@Override
public boolean dispatchKeyEvent(KeyEvent event) {//按鍵動作, //
TODO Auto-generated method stub
return super .dispatchKeyEvent(event); } }; timeDialog.setOnDismissListener(
new OnDismissListener() {//當Dialog消失時,做一些處理 //因為這個Dialog出現時,我把Activity隱藏了, //所以在Dialog消失時,我要把Activity顯示出來
@Override
public void onDismiss(DialogInterface dialog) { //
TODO Auto-generated method stub linearlayout_tvset_menu .setVisibility(View.
VISIBLE);//Activity顯示出來 linearlayout_set_time .requestFocus(); timeViewHolder =
null ;
} });
timeDialog.show();//Dialog建立完成後,要顯示的 4、在ViewHolder中使用Dialog的布局中的控制項:
private View root ;
private TextView tv_time_date ;
public TimeViewHolder(Context activity, View view) {
this .activity = activity;
this .root = view; tvTimerManager = TvTimerManager.
getInstance(); }
public void findViews() { tv_time_date = (TextView) root .findViewById(R.id.
tv_time_date); loadDataToUI(); } 5、收工