Android 实现点击缩略图查看大图的功能
1 思路分析
在本次项目的开发过程中,想实现这样一个常见功能,即点击页面上的小图查看大图,点击大图则关闭的功能。
该需求的实现思路一般有两种:一种是直接跳转到一个新的 activity 显示大图,另一种则是在原 activity 直接显示大图。这里介绍一种使用安卓原生对话框(dialog)实现该功能的方法。
2 实现方法
2.1 dialog 基本使用
dialog 是 Android 中一个常用组件,可以用于弹出提示框、选择框等功能。一个含有确定、取消和提示信息的普通 AlertDialog 使用方法如下:
final AlertDialog.Builder normalDialog = new AlertDialog.Builder(MainActivity.this);
normalDialog.setIcon(R.drawable.icon_dialog);
normalDialog.setTitle("Title")
normalDialog.setMessage("Test");
normalDialog.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//...To-do
}
});
normalDialog.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//...To-do
}
});
// 显示
normalDialog.show();
2.2 使用 dialog 实现查看大图功能
由于我们想在原 activity 中实现查看大图功能,那么可不可以借助 dailog 实现呢?dialog 提供了这样一个方法 setView()
,可以使我们自定义 dialog 的 View。既然如此,我们就可以利用该方法很简单地实现一个含有 ImageView
的对话框用于显示图片。
2.2.1 样式文件
首先,在 Activity 的样式文件中添加一个 ImageView 用作缩略图显示。
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:layout_marginTop="23dp"
android:orientation="horizontal">
<ImageView
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_marginLeft="10dp"
android:src="@drawable/default" />
</LinearLayout>
新建一个 dialog_photo.xml
文件,设置 dialog 的 View:
<?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="wrap_content">
<ImageView
android:id="@+id/large_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</LinearLayout>
2.2.2 实现逻辑
- 首先为 ImageView 设置点击事件
- 使用
dialog.setView(imgEntryView)
设置 dialog 的 View - 使用 Glide 为 ImageView 加载图片
LayoutInflater inflater = LayoutInflater.from(context);
View imgEntryView = inflater.inflate(R.layout.dialog_photo, null);
// 加载自定义的布局文件
final AlertDialog dialog = new AlertDialog.Builder(AssignmentDetailActivity.this).create();
ImageView img = (ImageView) imgEntryView.findViewById(R.id.large_image);
Glide.with(AssignmentDetailActivity.this).load(HttpClient.getPictureBaseUrl + url).into(img);
dialog.setView(imgEntryView); // 自定义dialog
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
其中,如果仅作以上设置,那么会发现弹出的对话框有一个很难看的白色背景,因此需要使用 setBackgroundDrawableResource()
设置对话框背景为透明即可:
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
我们不仅要实现点击缩略图查看大图,还要实现点击大图关闭对话框。因此为对话框的 View 再次设置对话框关闭事件:
// 点击大图关闭dialog
imgEntryView.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramView) {
dialog.cancel();
}
});