新建一个项目,首先界面布局,其代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bj1"
android:gravity="center">
<ImageButton
android:id="@+id/imageButton"
android:background="@drawable/duck1"
android:layout_width="120dp"
android:layout_height="135dp" />
</RelativeLayout>
然后在DuckActivity实现单击对应图片,跳出对应对话框
package com.example.duckapp;
import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class DuckActivity extends AppCompatActivity {
ImageButton imageButton;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_duck);
imageButton = (ImageButton)findViewById(R.id.imageButton);
//为按钮设置事件监听
imageButton.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View view) {
//对话框,Builder是AlertDialog的静态内部类
Dialog dialog = new AlertDialog.Builder(DuckActivity.this)
//设置对话框的标题
.setTitle("温情提示:")
//设置对话框要显示的内容
.setMessage("Hello,I'm duck!")
//给对话框加一个确定按钮,并且设置监听器
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//这里可以写确定按钮之后要执行的操作
return;
}
}).create();//创建按钮
dialog.show();
}
});
}
}