最近在項目中有一個用戶反饋的功能中要上傳圖片,和微信發朋友圈添加圖片的功能其實有點類似,所以我想着用GridView來實現這個功能,整個過程也很簡單,畫不多說,詳細步驟見下:
1.先來看MainActivity的佈局文件:activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="48dp"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
android:background="@drawable/aty_top_bg">
<TextView android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="圖片"/>
</android.support.v7.widget.Toolbar>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:background="@drawable/feedback_et_bg"
>
<GridView
android:id="@+id/grideView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="4"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:verticalSpacing="10dp"
>
</GridView>
</RelativeLayout>
</LinearLayout>
非常簡單,一個ToolBar+GridView,完事兒了!
2.接下來看下GridView的item的佈局:item_published_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:descendantFocusability="blocksDescendants"
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>
3.創建Adapter適配器GridViewAddImgesAdpter,在適配器中定義允許添加的最大圖片數,int maxImage;
在構造方法中獲取傳遞過來的數據:
public GridViewAddImgesAdpter(List<Map<String, String>> datas, Context context) {
this.datas = datas;
this.context = context;
inflater = LayoutInflater.from(context);
}
在getView方法中對datas進行判斷,如果當前position小於datas.size就加載傳遞過來的uri並加載,否則就加載“加載圖片”:
if (datas != null && position < datas.size()) {
String uri = datas.get(position).get("uri");
if (uri == null){
Log.e("adapter uri","adapter uri is null");
}
Uri uri1 = Uri.parse(uri);
// final File file = new File(datas.get(position).get("path").toString());
Glide.with(context)
.load(uri1)
.priority(Priority.HIGH)
.into(viewHolder.ivimage);
viewHolder.btdel.setVisibility(View.VISIBLE);
viewHolder.btdel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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);
}
加載圖片這裏我使用了Glide,也可以使用其他的加載框架,效果都是一樣的,別忘了加上依賴:
implementation 'com.github.bumptech.glide:glide:3.7.0'
對刪除按鈕的監聽也在上面的代碼裏了,比較簡單,大家一看就能明白,這裏就不贅述了
至此整個Adapter的代碼就基本完成了!
4.接下來就是在MainActivity中寫相關的代碼,在onCreat中初始化Adapter並給GridView設置Adapter,再給GridView的item設置點擊事件,當點擊的時候就彈出選擇框,跳轉至系統相機或者相冊:
gridViewAddImgesAdpter = new GridViewAddImgesAdpter(datas, this);
gridView.setAdapter(gridViewAddImgesAdpter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (position < datas.size()){
String uri = datas.get(position).get("uri");
Log.e("takepic uri","take uri5 :"+Uri.parse(uri));
Intent intent = new Intent(MainActivity.this, ImagePriviewActivity.class);
intent.putExtra("picUri", uri);
startActivity(intent);
}else{
showdialog();
}
}
});
showdialog()方法這裏就不貼代碼了,各位可以根據自己喜歡的樣式自由定製,下面直接貼上拍照和相冊選照片的代碼
5.調用相機和跳轉至相冊的方法:
調用相機:
public void takePic() {
File file = new File(IMAGE_DIR);
if (!file.exists()){
file.mkdir();
}
empFile = new File(file,System.currentTimeMillis() + "_" + PHOTO_FILE_NAME);
// Uri uri = Uri.fromFile(empFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", empFile));
// intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
// intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(empFile));
startActivityForResult(intent, TAKE_PIC);
}
跳轉至相冊:
public void localPic(){
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,LOCAL_PIC);
}
別忘了在清單文件中加上權限哦!
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
6.重寫onActivityResult方法,在改方法中將返回的數據進行包裝處理並添加到集合中去
if (resultCode == RESULT_OK){
if (requestCode == LOCAL_PIC){//相冊
uri = data.getData();
upLoadIamge(uri);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
if ( bitmap != null){
Log.e("null--bitmap1","bitmap1isnull:"+bitmap);
}
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == TAKE_PIC){//相機
// uri = Uri.fromFile(empFile);
if (empFile != null){
uri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", empFile);
upLoadIamge(uri);
}
}
}
這裏需要注意一下,有些編譯器的版本不一樣,在獲取uri的時候方法也不一樣,大家可以用Uri.fromFile來獲取,如果不行的話就換成下面的方法,如果是用下面的方法的話要注意,還要做如下兩步操作:
Manifest中添加如下代碼:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
在res下新建xml文件夾並創建provider_paths.xml文件,內容如下:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
7.將uri添加到集合中去,通過構造器傳遞給Adapter並調用notifyDataSetChanged通知數據的變化:
public void photoUri(String uri) {
if (uri == null){
Log.e("uri","uri is null:"+uri);
}
Map<String,String> map=new HashMap<>();
map.put("uri",uri);
datas.add(map);
gridViewAddImgesAdpter.notifyDataSetChanged();
}
8.以上代碼就可以實現調用相機或者相冊添加圖片至GridView中的功能了,哦,不要忘了 ,最後還有一個點擊圖片查看原圖,其實已經在設置itme監聽器的時候已經做了哈
if (position < datas.size()){
String uri = datas.get(position).get("uri");
Log.e("takepic uri","take uri5 :"+Uri.parse(uri));
Intent intent = new Intent(MainActivity.this, ImagePriviewActivity.class);
intent.putExtra("picUri", uri);
startActivity(intent);
}
這就是點擊查看預覽的方法啦,還要注意一點,這時候要在item的根佈局設置android:descendantFocusability="blocksDescendants"屬性,不然item的點擊事件和刪除按鈕的點擊事件會衝突的哦
9.預覽的界面很簡單,就是一個ImagePriviewActivity,一個ImageVIew來加載。佈局如下:
activity_priview.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/color_00"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_priview"
android:layout_width="360dp"
android:layout_height="480dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
ImagePriviewActivity中的代碼如下:
Intent intent = getIntent();
if (intent != null){
Uri uri = Uri.parse(intent.getStringExtra("picUri"));
Log.e("takepic uri","take uri6 :"+uri);
Glide.with(this).load(uri).into(imageView);
}
完事兒了!
10.以上就是使用GridView實現仿微信朋友圈添加、刪除、預覽圖片的全部內容,希望能對大家有所幫助,喜歡的話可以幫忙轉發點贊,有不足的地方希望大家指出並交流,謝謝大家!