Android GridView擴充套件仿微信微博發圖動態新增刪除圖片
阿新 • • 發佈:2019-02-01
在平時的開發中,我們會看到不管是微信發朋友圈照片還是微博釋出新鮮事,新增圖片的時候都是選完後面還有個+號再去選擇圖片,這樣的話比較方便使用者去新增圖片,有的右上角還有個-號方便使用者去刪除圖片,而一般使用者選擇的圖片多少都是不定的,我們只限制最大張數,我們用gridview去實現,程式碼可能比較簡單,高手請略過。
0.效果圖
1.準備資源圖片
- 新增圖片的+號圖片
刪除圖片的圖片
2.可設定限制使用者選擇最大張數
/**
* 可以動態設定最多上傳幾張,之後就不顯示+號了,使用者也無法上傳了
* 預設9張
*/
private int maxImages = 9;
/**
* 獲取最大上傳張數
*
* @return
*/
public int getMaxImages() {
return maxImages;
}
/**
* 設定最大上傳張數
*
* @param maxImages
*/
public void setMaxImages(int maxImages) {
this.maxImages = maxImages;
}
3.設定GridView的總數
/**
* 讓GridView中的資料數目加1最後一個顯示+號
* 當到達最大張數時不再顯示+號
* @return 返回GridView中的數量
*/
@Override
public int getCount() {
int count = datas == null ? 1 : datas.size() + 1;
if (count >= maxImages) {
return datas.size();
} else {
return count;
}
}
4.getView()中根據position判斷+號的顯示
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
/**代表+號之前的需要正常顯示圖片**/
if (datas != null && position < datas.size()) {
final File file = new File(datas.get(position).get("path").toString());
Glide.with(context)
.load(file)
.priority(Priority.HIGH)
.into(viewHolder.ivimage);
viewHolder.btdel.setVisibility(View.VISIBLE);
viewHolder.btdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (file.exists()) {
file.delete();
}
datas.remove(position);
notifyDataSetChanged();
}
});
} else {
/**代表+號的需要+號圖片顯示圖片**/
Glide.with(context)
.load(R.mipmap.image_add)
.priority(Priority.HIGH)
.centerCrop()
.into(viewHolder.ivimage);
viewHolder.ivimage.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolder.btdel.setVisibility(View.GONE);
}
return convertView;
}
5.GridView的完整程式碼
package cn.bluemobi.dylan.gridviewaddimage;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* com.bm.falvzixun.adapter.GridViewAddImgAdpter
*
* @author yuandl on 2015/12/24.
* 新增上傳圖片介面卡
*/
public class GridViewAddImgesAdpter extends BaseAdapter {
private List<Map<String, Object>> datas;
private Context context;
private LayoutInflater inflater;
/**
* 可以動態設定最多上傳幾張,之後就不顯示+號了,使用者也無法上傳了
* 預設9張
*/
private int maxImages = 9;
public GridViewAddImgesAdpter(List<Map<String, Object>> datas, Context context) {
this.datas = datas;
this.context = context;
inflater = LayoutInflater.from(context);
}
/**
* 獲取最大上傳張數
*
* @return
*/
public int getMaxImages() {
return maxImages;
}
/**
* 設定最大上傳張數
*
* @param maxImages
*/
public void setMaxImages(int maxImages) {
this.maxImages = maxImages;
}
/**
* 讓GridView中的資料數目加1最後一個顯示+號
* 當到達最大張數時不再顯示+號
* @return 返回GridView中的數量
*/
@Override
public int getCount() {
int count = datas == null ? 1 : datas.size() + 1;
if (count >= maxImages) {
return datas.size();
} else {
return count;
}
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
public void notifyDataSetChanged(List<Map<String, Object>> datas) {
this.datas = datas;
this.notifyDataSetChanged();
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_published_grida, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
/**代表+號之前的需要正常顯示圖片**/
if (datas != null && position < datas.size()) {
final File file = new File(datas.get(position).get("path").toString());
Glide.with(context)
.load(file)
.priority(Priority.HIGH)
.into(viewHolder.ivimage);
viewHolder.btdel.setVisibility(View.VISIBLE);
viewHolder.btdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (file.exists()) {
file.delete();
}
datas.remove(position);
notifyDataSetChanged();
}
});
} else {
/**代表+號的需要+號圖片顯示圖片**/
Glide.with(context)
.load(R.mipmap.image_add)
.priority(Priority.HIGH)
.centerCrop()
.into(viewHolder.ivimage);
viewHolder.ivimage.setScaleType(ImageView.ScaleType.FIT_XY);
viewHolder.btdel.setVisibility(View.GONE);
}
return convertView;
}
public class ViewHolder {
public final ImageView ivimage;
public final Button btdel;
public final View root;
public ViewHolder(View root) {
ivimage = (ImageView) root.findViewById(R.id.iv_image);
btdel = (Button) root.findViewById(R.id.bt_del);
this.root = root;
}
}
}
6.用法
- 主佈局檔案activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#FFFFFF"
android:orientation="vertical"
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="cn.bluemobi.dylan.gridviewaddimage.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="說點什麼"
android:textColor="#000000" />
<GridView
android:layout_marginTop="10dp"
android:id="@+id/gw"
android:numColumns="5"
android:horizontalSpacing="6dp"
android:columnWidth="60dp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
- gridview的item佈局檔案item_published_grida.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="66dp"
android:layout_height="66dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
android:scaleType="centerCrop"/>
<Button
android:id="@+id/bt_del"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:background="@drawable/bt_dynamic_del" />
</RelativeLayout>
</RelativeLayout>
- 彈出拍照和從相簿選擇的對話方塊佈局檔案dialog_add_picture.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5.0dip"
android:layout_marginRight="5.0dip"
android:background="@android:color/transparent"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="30px"
android:orientation="vertical">
<TextView
android:id="@+id/tv_camera"
android:layout_width="wrap_content"
android:layout_height="144px"
android:background="@mipmap/btn_top_arc"
android:gravity="center"
android:text="拍照"
android:textColor="#666666"
android:textSize="48px" />
<ImageView
android:layout_width="1022px"
android:layout_height="4px"
android:background="#666666" />
<TextView
android:id="@+id/tv_gallery"
android:layout_width="wrap_content"
android:layout_height="144px"
android:gravity="center"
android:background="@mipmap/btn_bottom_arc"
android:text="從手機相簿選擇"
android:textColor="#666666"
android:textSize="48px" />
</LinearLayout>
<TextView
android:id="@+id/tv_cancel"
android:layout_width="wrap_content"
android:layout_height="144px"
android:layout_marginTop="20px"
android:layout_marginLeft="30px"
android:layout_marginRight="30px"
android:layout_gravity="center_horizontal"
android:background="@mipmap/btn_top_arc"
android:gravity="center"
android:text="取消"
android:textColor="#666666"
android:textSize="48px" />
</LinearLayout>
- MainActivity
package cn.bluemobi.dylan.gridviewaddimage;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import net.bither.util.NativeUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private GridView gw;
private List<Map<String, Object>> datas;
private GridViewAddImgesAdpter gridViewAddImgesAdpter;
private Dialog dialog;
private final int PHOTO_REQUEST_CAREMA = 1;// 拍照
private final int PHOTO_REQUEST_GALLERY = 2;// 從相簿中選擇private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
private File tempFile;
private final String IMAGE_DIR = Environment.getExternalStorageDirectory() + "/gridview/";
/* 頭像名稱 */
private final String PHOTO_FILE_NAME = "temp_photo.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gw = (GridView) findViewById(R.id.gw);
datas = new ArrayList<>();
gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, this);
gw.setAdapter(gridViewAddImgesAdpter);
gw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
showdialog();
}
});
}
/**
* 選擇圖片對話方塊
*/
public void showdialog() {
View localView = LayoutInflater.from(this).inflate(
R.layout.dialog_add_picture, null);
TextView tv_camera = (TextView) localView.findViewById(R.id.tv_camera);
TextView tv_gallery = (TextView) localView.findViewById(R.id.tv_gallery);
TextView tv_cancel = (TextView) localView.findViewById(R.id.tv_cancel);
dialog = new Dialog(this, R.style.custom_dialog);
dialog.setContentView(localView);
dialog.getWindow().setGravity(Gravity.BOTTOM);
// 設定全屏
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.width = display.getWidth(); // 設定寬度
dialog.getWindow().setAttributes(lp);
dialog.show();
tv_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
tv_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
// 拍照
camera();
}
});
tv_gallery.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
// 從系統相簿選取照片
gallery();
}
});
}
/**
* 拍照
*/
public void camera() {
// 判斷儲存卡是否可以用,可用進行儲存
if (hasSdcard()) {
File dir = new File(IMAGE_DIR);
if (!dir.exists()) {
dir.mkdir();
}
tempFile = new File(dir,
System.currentTimeMillis() + "_" + PHOTO_FILE_NAME);
//從檔案中建立uri
Uri uri = Uri.fromFile(tempFile);
Intent intent = new Intent();
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addCategory(intent.CATEGORY_DEFAULT);
// 開啟一個帶有返回值的Activity,請求碼為PHOTO_REQUEST_CAREMA
startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
} else {
Toast.makeText(this, "未找到儲存卡,無法拍照!", Toast.LENGTH_SHORT).show();
}
}
/**
* 判斷sdcard是否被掛載
*/
public boolean hasSdcard() {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
}
/**
* 從相簿獲取2
*/
public void gallery() {
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PHOTO_REQUEST_GALLERY) {
// 從相簿返回的資料
if (data != null) {
// 得到圖片的全路徑
Uri uri = data.getData();
String[] proj = {MediaStore.Images.Media.DATA};
//好像是android多媒體資料庫的封裝介面,具體的看Android文件
Cursor cursor = managedQuery(uri, proj, null, null, null);
//按我個人理解 這個是獲得使用者選擇的圖片的索引值
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//將游標移至開頭 ,這個很重要,不小心很容易引起越界
cursor.moveToFirst();
//最後根據索引值獲取圖片路徑
String path = cursor.getString(column_index);
uploadImage(path);
}
} else if (requestCode == PHOTO_REQUEST_CAREMA) {
if (resultCode != RESULT_CANCELED) {
// 從相機返回的資料
if (hasSdcard()) {
if (tempFile != null) {
uploadImage(tempFile.getPath());
} else {
Toast.makeText(this, "相機異常請稍後再試!", Toast.LENGTH_SHORT).show();
}
Log.i("images", "拿到照片path=" + tempFile.getPath());
} else {
Toast.makeText(this, "未找到儲存卡,無法儲存照片!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0xAAAAAAAA) {
photoPath(msg.obj.toString());
}
}
};
/**
* 上傳圖片
*
* @param path
*/
private void uploadImage(final String path) {
new Thread() {
@Override
public void run() {
if (new File(path).exists()) {
Log.d("images", "原始檔存在" + path);
} else {
Log.d("images", "原始檔不存在" + path);
}
File dir = new File(IMAGE_DIR);
if (!dir.exists()) {
dir.mkdir();
}
final File file = new File(dir + "/temp_photo" + System.currentTimeMillis() + ".jpg");
NativeUtil.compressBitmap(path, file.getAbsolutePath(), 50);
if (file.exists()) {
Log.d("images", "壓縮後的檔案存在" + file.getAbsolutePath());
} else {
Log.d("images", "壓縮後的不存在" + file.getAbsolutePath());
}
Message message = new Message();
message.what = 0xAAAAAAAA;
message.obj = file.getAbsolutePath();
handler.sendMessage(message);
}
}.start();
}
public void photoPath(String path) {
Map<String,Object> map=new HashMap<>();
map.put("path",path);
datas.add(map);
gridViewAddImgesAdpter.notifyDataSetChanged();
}
}