Android自定义对话框Dialog以及主题和样式

自定义对话框Dialog、Android样式和主题

自定义对话框

首先需要为弹出的Dialog编写一个xml文件,确定对话框的样式
如一下为my_dialog.xml的代码:



android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="match_parent">
android:layout_gravity="center"
android:background="#ffffff"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
android:id="@+id/tv_title"
android:background="#0080FF"
android:gravity="center"
android:text="Custom Dialog"
android:textColor="#ffffff"
android:textSize="18sp"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="40dp" />
android:id="@+id/ll_content"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
android:id="@+id/tv_msg"
android:gravity="center"
android:minHeight="100dp"
android:paddingBottom="15dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="15dp"
android:textColor="#ff6666"
android:textSize="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />

android:layout_gravity="bottom"
android:background="#E0E0E0"
android:gravity="center"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="60dp">

dialog由 标题栏,内容显示区,确定取消按钮 三部分组成。

dialog的样式文件编写完成之后需要创建一个继承自android包下的Dialog的类(例如MyDialog),并加入构造函数,在MyDialog内的onCreate方法用setContentView方法将my_dialog.xml样式文件绑定,之后再MainActiivty中new MyDialog即可显示出对话框

样式与主题

创建一个样式需要在res/values/style目录下的styles.xml文件内定义,于该文件内加入如下代码:

<style name="textStyle_two" parent="@style/textStyle_one">
  <item name="android:textSize">25spitem>
style>

以上示例是为TextView标签定义的一种样式,可在TextView标签下加入style属性引用:

style=”@style/textStyle_two”

样式中parent指定的是另一个已定义的style,通过parent标签可以引入其中的样式属性。
实际开发中也可以自己创建样式文件,只要把文件创建在values目录下并以”.xml”结束,同时保持代码结构与style.xml一致即可

主题和样式再代码结构上是一样的,不同的是主题需要在AndroidManifest文件中引用,AndroidManifest文件中引用主题例子:

<activity
  android:name=".MainActivity"
  android:theme="@style/myTheme">
  ...
activity>

你可能感兴趣的:(Android)