Step 1:
首先设置登录界面 - dialog_login.xml
:用户名和密码输入框,以及清除按钮和登录按钮
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp"> <TableLayout android:id="@+id/dl_table" android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="1" android:visibility="visible" tools:layout_editor_absoluteX="8dp" tools:layout_editor_absoluteY="8dp"> <TableRow> <TextView android:layout_width="60dp" android:layout_height="wrap_content" android:gravity="center" android:text="用户" /> <EditText android:id="@+id/et_user" android:layout_width="match_parent" android:layout_height="wrap_content" /> </TableRow> <TableRow android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="60dp" android:layout_height="wrap_content" android:gravity="center" android:text="密码" /> <EditText android:id="@+id/et_password" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" /> </TableRow> </TableLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btn_clear" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="清除" /> <Button android:id="@+id/btn_login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="登录" /> </LinearLayout>
Step 2:
1. 将dialog_login.xml界面加载生成 View
对象;
2. 生成 dialog
对象,将自定义视图加载进去;
3. 显示该登录对话框;
public class CustomActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom); View view = View.inflate(this, R.layout.dialog_login, null); AlertDialog.Builder builder = new AlertDialog.Builder(this).setView(view); builder.show(); } }
Note:调用 builder.show
等同于先创建 AlertDialog
,再进行显示
这样就完成了登录对话框的创建,如果想要进一步获取用户输入的信息,点击按钮可以进行操作,增加如下代码: