在做Android平台的APP时候,经常会遇到自定义弹出对话框,在Android中,已经预先给我们设置了几种弹出对话框的接口DialogBuilder ,今天闲来无事,特意整理了一下,方便日后学习回顾。
1.这是一个最简单的应用,就是弹出一个消息框,先看效果:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/hello_world">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="你好"
android:id="@+id/text"
android:focusableInTouchMode="true"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="确定"
android:id="@+id/button" />
</LinearLayout>
MainActivity.java
package com.example.sm.myapplication;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Button button;
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("确认" ) ;
editText = (EditText)findViewById(R.id.text);
builder.setMessage(editText.getText().toString()) ;
builder.setPositiveButton("是" , null );
builder.show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}