对话框风格的窗口

     还有一种自定义对话框的方式,这种对话框本质上依然是窗口,只是把显示窗口的Activity的风格设为对话框风格即可。

     下面的程序定义一个简单的界面布局,该界面布局里包含一个ImageView和一个Button。接下来程序使用Activity来显示该界面布局。

     该界面布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
     >
<ImageView android:layout_width="500dp"
    android:layout_height="300dp"
    android:src="@drawable/android"/>
   <Button android:id="@+id/bn"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="确定"/>
</LinearLayout>

后台代码文件如下:

package org.crazyit.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DialogTheme extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_theme);
        Button bn=(Button)findViewById(R.id.bn);
        //为按钮绑定事件监听器
        bn.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //结束该Activity
                finish();
            }
            
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.dialog_theme, menu);
        return true;
    }

}

上面的程序仅仅是为界面上的按钮绑定了事件监听器,当该按钮被单击时结束该Activity。

接下里在AndroidManifest.xml文件中指定该窗口以对话框风格显示,也就是在清单文件中使用如下配置片段:

 

  <activity
            android:name="org.crazyit.helloworld.DialogTheme"
            android:label="@string/title_activity_dialog_theme"
            android:theme="@android:style/Theme.Dialog" >
            <intent-filter>

                <action android:name="android.intent.action.MAIN" /> 


              <category android:name="android.intent.category.LAUNCHER" /> 
            </intent-filter>
        </activity>

上面的粗体字代码指定DialogTeme使用对话框风格进行显示。运行上面的程序,将看到如图所示界面。

原文地址:https://www.cnblogs.com/wolipengbo/p/3394052.html