這篇文章給大家分享的是有關(guān)Android中GridView擴(kuò)展如何實(shí)現(xiàn)微信微博發(fā)圖動(dòng)態(tài)添加刪除圖片功能的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來(lái)自于我們對(duì)這個(gè)行業(yè)的熱愛(ài)。我們立志把好的技術(shù)通過(guò)有效、簡(jiǎn)單的方式提供給客戶,將通過(guò)不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長(zhǎng)期合作伙伴,公司提供的服務(wù)項(xiàng)目有:主機(jī)域名、雅安服務(wù)器托管、營(yíng)銷軟件、網(wǎng)站建設(shè)、大慶網(wǎng)站維護(hù)、網(wǎng)站推廣。
在平時(shí)的開(kāi)發(fā)中,我們會(huì)看到不管是微信發(fā)朋友圈照片還是微博發(fā)布新鮮事,添加圖片的時(shí)候都是選完后面還有個(gè)+號(hào)再去選擇圖片,這樣的話比較方便用戶去添加圖片,有的右上角還有個(gè)-號(hào)方便用戶去刪除圖片,而一般用戶選擇的圖片多少都是不定的,我們只限制最大張數(shù),我們用gridview去實(shí)現(xiàn),代碼可能比較簡(jiǎn)單,高手請(qǐng)略過(guò)。
0.效果圖
1.準(zhǔn)備資源圖片
添加圖片的+號(hào)圖片
刪除圖片的圖片
2.可設(shè)置限制用戶選擇最大張數(shù)
/** * 可以動(dòng)態(tài)設(shè)置最多上傳幾張,之后就不顯示+號(hào)了,用戶也無(wú)法上傳了 * 默認(rèn)9張 */ private int maxImages = 9; /** * 獲取最大上傳張數(shù) * * @return */ public int getMaxImages() { return maxImages; } /** * 設(shè)置最大上傳張數(shù) * * @param maxImages */ public void setMaxImages(int maxImages) { this.maxImages = maxImages; }
3.設(shè)置GridView的總數(shù)
/** * 讓GridView中的數(shù)據(jù)數(shù)目加1最后一個(gè)顯示+號(hào) * 當(dāng)?shù)竭_(dá)最大張數(shù)時(shí)不再顯示+號(hào) * @return 返回GridView中的數(shù)量 */ @Override public int getCount() { int count = datas == null ? 1 : datas.size() + 1; if (count >= maxImages) { return datas.size(); } else { return count; } }
4.getView()中根據(jù)position判斷+號(hào)的顯示
@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(); } /**代表+號(hào)之前的需要正常顯示圖片**/ 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 { /**代表+號(hào)的需要+號(hào)圖片顯示圖片**/ 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
6.用法
主布局文件activity_main.xml
gridview的item布局文件item_published_grida.xml
彈出拍照和從相冊(cè)選擇的對(duì)話框布局文件dialog_add_picture.xml
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> datas; private GridViewAddImgesAdpter gridViewAddImgesAdpter; private Dialog dialog; private final int PHOTO_REQUEST_CAREMA = 1;// 拍照 private final int PHOTO_REQUEST_GALLERY = 2;// 從相冊(cè)中選擇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(); } }); } /** * 選擇圖片對(duì)話框 */ 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); // 設(shè)置全屏 WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); lp.width = display.getWidth(); // 設(shè)置寬度 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(); // 從系統(tǒng)相冊(cè)選取照片 gallery(); } }); } /** * 拍照 */ public void camera() { // 判斷存儲(chǔ)卡是否可以用,可用進(jìn)行存儲(chǔ) if (hasSdcard()) { File dir = new File(IMAGE_DIR); if (!dir.exists()) { dir.mkdir(); } tempFile = new File(dir, System.currentTimeMillis() + "_" + PHOTO_FILE_NAME); //從文件中創(chuàng)建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); // 開(kāi)啟一個(gè)帶有返回值的Activity,請(qǐng)求碼為PHOTO_REQUEST_CAREMA startActivityForResult(intent, PHOTO_REQUEST_CAREMA); } else { Toast.makeText(this, "未找到存儲(chǔ)卡,無(wú)法拍照!", Toast.LENGTH_SHORT).show(); } } /** * 判斷sdcard是否被掛載 */ public boolean hasSdcard() { return Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED); } /** * 從相冊(cè)獲取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) { // 從相冊(cè)返回的數(shù)據(jù) if (data != null) { // 得到圖片的全路徑 Uri uri = data.getData(); String[] proj = {MediaStore.Images.Media.DATA}; //好像是android多媒體數(shù)據(jù)庫(kù)的封裝接口,具體的看Android文檔 Cursor cursor = managedQuery(uri, proj, null, null, null); //按我個(gè)人理解 這個(gè)是獲得用戶選擇的圖片的索引值 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); //將光標(biāo)移至開(kāi)頭 ,這個(gè)很重要,不小心很容易引起越界 cursor.moveToFirst(); //最后根據(jù)索引值獲取圖片路徑 String path = cursor.getString(column_index); uploadImage(path); } } else if (requestCode == PHOTO_REQUEST_CAREMA) { if (resultCode != RESULT_CANCELED) { // 從相機(jī)返回的數(shù)據(jù) if (hasSdcard()) { if (tempFile != null) { uploadImage(tempFile.getPath()); } else { Toast.makeText(this, "相機(jī)異常請(qǐng)稍后再試!", Toast.LENGTH_SHORT).show(); } Log.i("images", "拿到照片path=" + tempFile.getPath()); } else { Toast.makeText(this, "未找到存儲(chǔ)卡,無(wú)法存儲(chǔ)照片!", 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 map=new HashMap<>(); map.put("path",path); datas.add(map); gridViewAddImgesAdpter.notifyDataSetChanged(); } }
感謝各位的閱讀!關(guān)于“Android中GridView擴(kuò)展如何實(shí)現(xiàn)微信微博發(fā)圖動(dòng)態(tài)添加刪除圖片功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!