系列博客持续更新,欢迎关注和收藏。
最近用到类似苹果悬浮按钮这种非全屏显示的界面,于是第一想到的是利用自定义Dialog来实现,写了一个自定义Dialog的最简单的Demo。
先上效果图。
实现的效果是,打开软件,显示的是后面的那个按钮,点击按钮,显示的是前面的这个对话框,可以接受数据和点击。
之前的那些新建工程,定义Button,添加监听,暂时略过。
实现步骤:
1 定义dialog的layout
在res/layouts路径下,新建一个layout文件,名字为dialog.xml.在里面定义控件和位置即可
我的Demo里的是这样的
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="用户名"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="密码"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录"
/>
</LinearLayout>
2 新建一个class,名字暂时定为MyDialog,重点是要继承Dialog类,实现他的构造函数和OnCreate()方法,在里面指定要Dialog用的layout,具体代码贴出来
public class MyDialog extends Dialog{
//这个是为了给对话框添加监听用的,这个demo暂时不演示
Context context;
public MyDialog(Context context) {
super(context);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//设置dialog的layout
this.setContentView(R.layout.dialog);
}
}
3 在主界面的Button监听器中添加Dialog的调用函数,代码如下
Dialog dialog = new MyDialog(MainActivity.this);
//设置对话框的标题
dialog.setTitle("用户登录");
//显示对话框
dialog.show();
到此为止,一个自定义的对话框就已经可以显示了,只是还没有添加对应的监听函数,至少显示信息可以了。
下面是我写的简单Demo