天天看點

Activity實作自定義Dialog

在Android中可以直接使用Dialog實作提示視窗。也可以使用Activity來實作自定義的dialog。本文就是使用Activity來實作一個自定義的Dialog。

主類的實作如下:

package com.xiaochun91103;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class CustomerDialog extends Activity {

/** Called when the activity is first created. */

private Button bt;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

bt = (Button)findViewById(R.id.bt);

bt.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

Intent intent = new Intent(CustomerDialog.this,DialogActivity.class);

startActivity(intent);

}

});

}

}

布局如下,main.xml:

 <?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="用于自定義一個Activity的主題來實作使用者自定義Dialog"

/>

<Button

android:id="@+id/bt"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="DialogTest"

/>

</LinearLayout>

Dialog類的實作如下:

package com.xiaochun91103;

import android.app.Activity;

import android.os.Bundle;

public class DialogActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.dialogactivity);

}

}

布局如下dialogactivity.xml:

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text"

android:layout_width="fill_parent" android:layout_height="fill_parent"

android:gravity="center_vertical|center_horizontal"

android:text="customer activity looks like a dialog.customer dialog test!!!"

android:background="#992222"/>

最重要的一點,需要在AndroidManifest.xml下聲明Activity的同時定義Activity的主題,這樣才會出現Dialog的效果。

<activity android:name=".DialogActivity"

android:theme="@android:style/Theme.Dialog"> </activity>

上個截圖:

Activity實作自定義Dialog