[Android] 通過(guò)GridView仿微信動(dòng)態(tài)添加本地圖片示例代碼
前面文章講述的都是"隨手拍"中圖像處理的操作,此篇文章主要講述GridView控件實(shí)現(xiàn)添加本地圖片并顯示.主要是關(guān)于GridView控件的基本操作,通常可以通過(guò)自定義繼承BaseAdapter的適配器加載圖片,而下面講述的不是自定義的適配器,而是調(diào)用SimpleAdapter實(shí)現(xiàn)的.至于上傳發(fā)布與網(wǎng)絡(luò)交互此處不講述,后面文章會(huì)講!
一. 實(shí)現(xiàn)效果
主要是通過(guò)點(diǎn)擊+從本地相冊(cè)中添加圖片,同時(shí)顯示圖片至GridView.點(diǎn)擊圖片可以進(jìn)行刪除操作,同時(shí)界面中的發(fā)布EditView控件也很好看,不足之處在于+好沒(méi)有移動(dòng)至最后,但原理相同.
二. 項(xiàng)目工程結(jié)構(gòu)

三. 界面布局詳細(xì)代碼
1.主界面activity_main.xml
主要通過(guò)相對(duì)布局實(shí)現(xiàn),第一部分是底部的TextView,中間是EditView和GridView相對(duì)布局,下面是兩個(gè)按鈕.同時(shí)EditView調(diào)用res/drawable-hdpi中的editview_shape.xml,GridView顯示的每張圖片通過(guò)griditem_addpic.xml實(shí)現(xiàn).
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.suishoupaipublish.MainActivity"
tools:ignore="MergeRootFrame" >
<!-- 頂部添加文字 -->
<RelativeLayout
android:id="@+id/Layout_top"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_alignParentTop="true"
android:gravity="center">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:gravity="center"
android:text="發(fā)布信息" />
</RelativeLayout>
<!-- 底部按鈕 -->
<RelativeLayout
android:id="@+id/Layout_bottom"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:gravity="center" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textSize="20sp"
android:text="發(fā)布拍拍" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_toRightOf="@+id/button1"
android:textSize="20sp"
android:text="取消發(fā)布" />
</RelativeLayout>
<!-- 顯示圖片 -->
<RelativeLayout
android:id="@+id/Content_Layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/Layout_bottom"
android:layout_below="@id/Layout_top"
android:gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentBottom="true" >
<!-- 設(shè)置運(yùn)行多行 設(shè)置圓角圖形 黑色字體-->
<EditText
android:id="@+id/editText1"
android:layout_height="120dp"
android:layout_width="fill_parent"
android:textColor="#000000"
android:layout_margin="12dp"
android:textSize="20sp"
android:hint="隨手說(shuō)出你此刻的心聲..."
android:maxLength="500"
android:singleLine="false"
android:background="@drawable/editview_shape" />
<!-- 網(wǎng)格顯示圖片 行列間距5dp 每列寬度90dp -->
<GridView
android:id="@+id/gridView1"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_margin="10dp"
android:background="#EFDFDF"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:numColumns="4"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center" >
</GridView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="(友情提示:只能添加9張圖片,長(zhǎng)按圖片可以刪除已添加圖片)"
android:gravity="center" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
2.顯示ImageView圖片布局griditem_addpic.xml
<?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="match_parent"
android:gravity="center"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical" >
<RelativeLayout
android:layout_gravity="center"
android:layout_width="80dp"
android:layout_height="80dp"
android:orientation="vertical" >
<ImageView
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:id="@+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
android:src="@drawable/gridview_addpic" />
</RelativeLayout>
</LinearLayout>
3.設(shè)置EditView控件圓角和顏色 editview_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:padding="10dp">
<!-- 填充editView的顏色 -->
<soild android:color="#ffffff"/>
<!-- 設(shè)置圓角的弧度,radius半徑越大,editView的邊角越圓 -->
<corners
android:radius="15dp"
android:bottomRightRadius="15dp"
android:bottomLeftRadius="15dp"
android:topLeftRadius="15dp"
android:topRightRadius="15dp"/>
<stroke
android:color="#32CD32"
android:width="4px" />
</shape>
四. 代碼詳解
它主要是思想如下:
1.通過(guò)SimpleAdapter適配器實(shí)現(xiàn)實(shí)現(xiàn)加載圖片,在gridView1.setOnItemClickListener()點(diǎn)擊函數(shù)中響應(yīng)不同操作.
2.當(dāng)點(diǎn)擊加號(hào)圖片(+)時(shí),調(diào)用本地相冊(cè)通過(guò)Intent實(shí)現(xiàn)獲取圖片路徑存于字符串pathImage.
3.獲取圖片路徑后在onResume中刷新圖片,通過(guò)GridView的setAdapter()和notifyDataSetChanged()()函數(shù)刷新加載圖片.
4.點(diǎn)擊圖片時(shí)會(huì)獲取其position,通過(guò)dialog()函數(shù)彈出對(duì)話框提示是否刪除,通過(guò)remove實(shí)現(xiàn)刪除.
具體代碼如下所示:
public class MainActivity extends Activity {
private GridView gridView1; //網(wǎng)格顯示縮略圖
private Button buttonPublish; //發(fā)布按鈕
private final int IMAGE_OPEN = 1; //打開(kāi)圖片標(biāo)記
private String pathImage; //選擇圖片路徑
private Bitmap bmp; //導(dǎo)入臨時(shí)圖片
private ArrayList<HashMap<String, Object>> imageItem;
private SimpleAdapter simpleAdapter; //適配器
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* 防止鍵盤擋住輸入框
* 不希望遮擋設(shè)置activity屬性 android:windowSoftInputMode="adjustPan"
* 希望動(dòng)態(tài)調(diào)整高度 android:windowSoftInputMode="adjustResize"
*/
getWindow().setSoftInputMode(WindowManager.LayoutParams.
SOFT_INPUT_ADJUST_PAN);
//鎖定屏幕
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
//獲取控件對(duì)象
gridView1 = (GridView) findViewById(R.id.gridView1);
/*
* 載入默認(rèn)圖片添加圖片加號(hào)
* 通過(guò)適配器實(shí)現(xiàn)
* SimpleAdapter參數(shù)imageItem為數(shù)據(jù)源 R.layout.griditem_addpic為布局
*/
//獲取資源圖片加號(hào)
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gridview_addpic);
imageItem = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("itemImage", bmp);
imageItem.add(map);
simpleAdapter = new SimpleAdapter(this,
imageItem, R.layout.griditem_addpic,
new String[] { "itemImage"}, new int[] { R.id.imageView1});
/*
* HashMap載入bmp圖片在GridView中不顯示,但是如果載入資源ID能顯示 如
* map.put("itemImage", R.drawable.img);
* 解決方法:
* 1.自定義繼承BaseAdapter實(shí)現(xiàn)
* 2.ViewBinder()接口實(shí)現(xiàn)
*/
simpleAdapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// TODO Auto-generated method stub
if(view instanceof ImageView && data instanceof Bitmap){
ImageView i = (ImageView)view;
i.setImageBitmap((Bitmap) data);
return true;
}
return false;
}
});
gridView1.setAdapter(simpleAdapter);
/*
* 監(jiān)聽(tīng)GridView點(diǎn)擊事件
* 報(bào)錯(cuò):該函數(shù)必須抽象方法 故需要手動(dòng)導(dǎo)入import android.view.View;
*/
gridView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
if( imageItem.size() == 10) { //第一張為默認(rèn)圖片
Toast.makeText(MainActivity.this, "圖片數(shù)9張已滿", Toast.LENGTH_SHORT).show();
}
else if(position == 0) { //點(diǎn)擊圖片位置為+ 0對(duì)應(yīng)0張圖片
Toast.makeText(MainActivity.this, "添加圖片", Toast.LENGTH_SHORT).show();
//選擇圖片
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMAGE_OPEN);
//通過(guò)onResume()刷新數(shù)據(jù)
}
else {
dialog(position);
//Toast.makeText(MainActivity.this, "點(diǎn)擊第"+(position + 1)+" 號(hào)圖片",
// Toast.LENGTH_SHORT).show();
}
}
});
}
//獲取圖片路徑 響應(yīng)startActivityForResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//打開(kāi)圖片
if(resultCode==RESULT_OK && requestCode==IMAGE_OPEN) {
Uri uri = data.getData();
if (!TextUtils.isEmpty(uri.getAuthority())) {
//查詢選擇圖片
Cursor cursor = getContentResolver().query(
uri,
new String[] { MediaStore.Images.Media.DATA },
null,
null,
null);
//返回 沒(méi)找到選擇圖片
if (null == cursor) {
return;
}
//光標(biāo)移動(dòng)至開(kāi)頭 獲取圖片路徑
cursor.moveToFirst();
pathImage = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
}
} //end if 打開(kāi)圖片
}
//刷新圖片
@Override
protected void onResume() {
super.onResume();
if(!TextUtils.isEmpty(pathImage)){
Bitmap addbmp=BitmapFactory.decodeFile(pathImage);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("itemImage", addbmp);
imageItem.add(map);
simpleAdapter = new SimpleAdapter(this,
imageItem, R.layout.griditem_addpic,
new String[] { "itemImage"}, new int[] { R.id.imageView1});
simpleAdapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// TODO Auto-generated method stub
if(view instanceof ImageView && data instanceof Bitmap){
ImageView i = (ImageView)view;
i.setImageBitmap((Bitmap) data);
return true;
}
return false;
}
});
gridView1.setAdapter(simpleAdapter);
simpleAdapter.notifyDataSetChanged();
//刷新后釋放防止手機(jī)休眠后自動(dòng)添加
pathImage = null;
}
}
/*
* Dialog對(duì)話框提示用戶刪除操作
* position為刪除圖片位置
*/
protected void dialog(final int position) {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage("確認(rèn)移除已添加圖片嗎?");
builder.setTitle("提示");
builder.setPositiveButton("確認(rèn)", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
imageItem.remove(position);
simpleAdapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
同時(shí)需要在AndroidMainfest.xml中添加權(quán)限操作SD卡和網(wǎng)絡(luò)上傳至服務(wù)器.
<!-- 申明網(wǎng)絡(luò)權(quán)限 --> <uses-permission android:name="android.permission.INTERNET" /> <!-- 申明權(quán)限 操作SD卡 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
五. 總結(jié)
該文章需要注意一個(gè)地方:在使用SimpleAdapter適配器加載bmp圖片時(shí),可能在GridView中不顯示.即HashMap中map.put("itemImage",bmp)不顯示圖片,而使用put裝入R.drawable.img卻能顯示.
這時(shí)有兩種解決方法,一種是自定義繼承BaseAdapter的適配器實(shí)現(xiàn);另一種方法則是如上所示通過(guò)ViewBinder()接口實(shí)現(xiàn),感謝博主dmin_提供的方法.
demo下載地址:http://xiazai.jb51.net/201701/yuanma/GirdViewTest_jb51.rar
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android Studio使用recyclerview實(shí)現(xiàn)展開(kāi)和折疊功能(在之前的微信頁(yè)面基礎(chǔ)之上)
這篇文章主要介紹了Android Studio使用recyclerview實(shí)現(xiàn)展開(kāi)和折疊(在之前的微信頁(yè)面基礎(chǔ)之上),本文通過(guò)截圖實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2020-03-03
Android編程之播放器MediaPlayer實(shí)現(xiàn)均衡器效果示例
這篇文章主要介紹了Android編程之播放器MediaPlayer實(shí)現(xiàn)均衡器效果,結(jié)合具體實(shí)例形式分析了Android調(diào)用MediaPlayer相關(guān)API構(gòu)造均衡器的具體步驟與相關(guān)功能實(shí)現(xiàn)方法,需要的朋友可以參考下2017-08-08
Android 用戶Session管理的設(shè)計(jì)方案
這篇文章主要介紹了Android 用戶Session管理的設(shè)計(jì)方案,需要的朋友可以參考下2017-12-12
Android實(shí)現(xiàn)短信驗(yàn)證碼輸入框
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)短信驗(yàn)證碼輸入框,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
Android編程之簡(jiǎn)單計(jì)時(shí)器實(shí)現(xiàn)方法
這篇文章主要介紹了Android編程之簡(jiǎn)單計(jì)時(shí)器實(shí)現(xiàn)方法,涉及Android開(kāi)發(fā)中ContextMenu及Chronometer的相關(guān)使用技巧,需要的朋友可以參考下2016-01-01
android避免彈出軟鍵盤遮蓋listview的簡(jiǎn)單方法
下面小編就為大家?guī)?lái)一篇android避免彈出軟鍵盤遮蓋listview的簡(jiǎn)單方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09
Android獲取手機(jī)型號(hào)/系統(tǒng)版本號(hào)/App版本號(hào)等信息實(shí)例講解
本示例獲得手機(jī)型號(hào),系統(tǒng)版本,App版本號(hào)等信息,具體實(shí)現(xiàn)如下,感興趣的朋友可以參考下哈2013-06-06
Android 類似UC瀏覽器的效果:向上滑動(dòng)地址欄隱藏功能
這篇文章主要介紹了Android 類似UC瀏覽器的效果:向上滑動(dòng)地址欄隱藏功能,需要的朋友可以參考下2017-12-12

