自定义对话框
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.a2_.MainActivity">
<Button
android:text="长按展示对话框"
android:id="@+id/btn_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
自定义对话框布局
<?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:id="@+id/tv_delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="点我删除"
android:textSize="14sp"/>
<TextView
android:id="@+id/tv_top"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="点我置顶"
android:textSize="14sp"/>
</LinearLayout>
核心代码
package com.example.a2_;
import android.app.Dialog;
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.Toast;
public class MainActivity extends AppCompatActivity {
private Button btn_show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
btn_show = (Button) findViewById(R.id.btn_show);
//设置长按点击事件
btn_show.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
showDialog();
return false;
}
});
}
//显示对话框
private void showDialog() {
//创建对话框
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//将自定义的对话框布局转化为View对象
View view = View.inflate(this, R.layout.dialog_item, null);
//将view引入到对话框中
builder.setView(view);
//构建出对话框
final AlertDialog dialog = builder.create();
//创建删除事件
view.findViewById(R.id.tv_delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "删除", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
//创建置顶事件
view.findViewById(R.id.tv_top).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "置顶", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();
}
}