如果想要想要跳出一個畫面, 又不想處理複雜的生命周期,
其實Dialog是你的好朋友。
我也蠻建議最好一隻程式, 不要開太多Activity,
之前在寫專案的時候, 就是因為開太多Activity, 所以效能大爆炸。
而最單純的頁面就是Dialog, 只要呼叫它, 就不用太多複雜的事情要處理。
如果要做管理, 其實他就是疊加在上一層畫面, 可以在建立的時候,
就決定該層畫面是否要關閉, 非常方便。
一開始建立一個很簡單的畫面, 只要有一個Button在上面,
按下去以後, 就會跳出我們自訂的Dialog。
private Button showDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog = (Button) findViewById(R.id.show_dialog);
showDialog.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new MyDialog(MainActivity.this).show();
}
});
}
那接著就實做我們的Dialog
public class MyDialog extends Dialog{
public MyDialog(Context context) {
super(context, android.R.style.Theme_Light);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_layout);
}
}
就這麼簡單? 沒錯!
而且只需要呼叫show(); 就可以把畫面叫出來了。
白茫茫的一片, 好空虛。
加個背景顏色跟文字好了。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff000" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hi"
/>
</RelativeLayout>
這樣就有背景顏色跟文字了, 內容想放什麼都可以,
之後在寫一篇如何傳遞資訊跟即時關閉。