MaterialTest学习笔记(四)感谢郭神
如何使用AlertDialog以及添加在其中输入框
首先看一下效果图:
新建一个空白Activity
修改activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button"/>
</android.support.constraint.ConstraintLayout>
修改MainActivity.class
package com.example.dialogt;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button_dialog);
}
@Override
protected void onStart() {
super.onStart();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//首先添加一个edit实例,然后通过dialog设置显示
final EditText editText = new EditText(MainActivity.this);
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("这是标题");
dialog.setView(editText);
dialog.setCancelable(false);
dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"填写确定监听事件",Toast.LENGTH_SHORT).show();
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
});
}
}
到此本篇功能实现。