編輯:關於 Android 程式設計
動手寫程式之前,先把需求與邏輯梳理清楚,後續的思路就會清晰許多。這裡要實現的功能如下:
1. 多圖上傳首先得能選圖(此專案要求既支援拍照上傳,也支援從相冊挑選)。
2. 拍照上傳相對簡單,網路上範例很多,本質上就是呼叫相機、取得回傳的 URI,再讀取圖片。
3. 從相冊中挑選圖片,則需要:
整體邏輯大致如此,下面看具體實作。
<com.view.NoScrollGridView android:id="@+id/noScrollgridview" android:layout_marginLeft="@dimen/smaller_space" android:layout_marginRight="@dimen/smaller_space" android:layout_width="match_parent" android:layout_height="wrap_content" android:horizontalSpacing="3dp" android:listSelector="@color/transparent" android:numColumns="3" android:scrollbars="none" android:layout_gravity="center" android:layout_marginTop="@dimen/smaller_space" android:verticalSpacing="5dp" />
這裡使用的是 NoScrollGridView,也就是不具捲動能力的 GridView,是專案需求所致;一般情況下直接用 GridView 即可。
noScrollgridview = (GridView) findViewById(R.id.noScrollgridview); noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT)); /*新建傳值給adapter*/ if (file == null) { picAdapter = new PictureAdapter(this, 0, null); } else { //添加失敗的圖片到數組中 for (int i=0;i<file.getMulFailFilePaths().length;i++){ ImageItem imageItem = new ImageItem(); imageItem.setImagePath(file.getMulFailFilePaths()[i].trim()); Bimp.tempSelectBitmap.add(imageItem); } /*上傳失敗傳值給adapter*/ picAdapter = new PictureAdapter(this, 2, file); }
這段是初始化圖片陣列與 Adapter(新建、上傳失敗、上傳成功三種狀態共用同一個 Adapter)。
ImageItem 是圖片的模型類,其屬性如下:
//從圖庫選擇的圖片model public class ImageItem extends File implements Serializable { @Id public String imageId; //圖片id public String thumbnailPath; public String imagePath; //圖片路徑 private Bitmap bitmap; public boolean isSelected = false; public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public String getThumbnailPath() { return thumbnailPath; } public void setThumbnailPath(String thumbnailPath) { this.thumbnailPath = thumbnailPath; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public boolean isSelected() { return isSelected; } public void setSelected(boolean isSelected) { this.isSelected = isSelected; } [java] view plain copy print? /*根據圖片路徑獲取圖片的bitmap*/ public Bitmap getBitmap() { if(bitmap == null){ try { bitmap = Bimp.revitionImageSize(imagePath); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; }
接著是 Adapter:
由於涉及新增圖片,Adapter 中透過一個 flag 來區分新建圖片的顯示邏輯,並把選取的圖片加入公用陣列,初始化時載入陣列呈現(閱讀時可先忽略我的 flag)。
@SuppressLint("HandlerLeak") public class PictureAdapter extends BaseAdapter { private LayoutInflater inflater; private int selectedPosition = -1; private boolean shape; private int flag = 0;//0 默認新建 1上傳成功 2上傳失敗 private AppItem_file file; public boolean isShape() { return shape; } private Activity context; public void setShape(boolean shape) { this.shape = shape; } public PictureAdapter(Activity context,int flag,AppItem_file file) { this.context = context; inflater = LayoutInflater.from(context); this.flag = flag; this.file = file; } // public void update() { // loading(); // } public int getCount() { if (flag==0){ //新建圖片 if (Bimp.tempSelectBitmap.size() == 6) { return 6; } return (Bimp.tempSelectBitmap.size() + 1); } else if (flag==1){ //上傳成功 return file.getFileList().size(); } else { //上傳失敗 return file.getMulFailFilePaths().length; } } public Object getItem(int arg0) { if (flag==1){ return file.getFileList().get(arg0); }else { return file.getMulFailFilePaths()[arg0]; } } public long getItemId(int arg0) { return arg0; } public void setSelectedPosition(int position) { selectedPosition = position; } public int getSelectedPosition() { return selectedPosition; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { //根據圖片的數量加載不同布局 if (getCount()==1&&flag!=0){ convertView = inflater.inflate(R.layout.item_published_singal_item, parent, false); } else { convertView = inflater.inflate(R.layout.item_published_grida, parent, false); } holder = new ViewHolder(); holder.image = (ImageView) convertView .findViewById(R.id.item_grida_image); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } /** * 根據初始化adapter傳過來的flag值,去不同的地方找圖片 * flag=0,去Bimp的圖片數組中找 * flag=1,證明上傳成功的,去下載好的getFileList中找 * flag=2,為上傳失敗的,圖片保存在FailFile中的List<ImageItem>中 * 優化圖片顯示 */ if (flag==0){ //新建圖片 if (position == Bimp.tempSelectBitmap.size()) { holder.image.setImageBitmap(BitmapFactory.decodeResource( convertView.getResources(), R.drawable.icon_add_pic_unfocused)); if (position == 6) { if (flag==0){ holder.image.setVisibility(View.GONE); } } } else { holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position).getBitmap()); } } else if (flag==1){ //上傳成功 // List<Integer> ids = new ArrayList<Integer>(); // for (int i=0;i<file.getFileList().size();i++){ // ids.add(file.getFileList().get(i).getS_id()); // } int id=file.getFileList().get(position).getS_id(); try { // File file= NeedApplication.db.findById(File.class,id); String fileBigImgUri =NeedApplication.db.findById(File.class,id).getFileUriBig(); if (fileBigImgUri!=null&&!"null".equals(fileBigImgUri)) ImageLoader.getInstance().displayImage((fileBigImgUri).trim(),holder.image); } catch (DbException e) { e.printStackTrace(); } } else { //上傳失敗 String url = "file://"+file.getMulFailFilePaths()[position].trim(); ImageLoader.getInstance().displayImage(url, holder.image); } return convertView; } public class ViewHolder { public ImageView image; } }
下面是自訂的相冊介面,用來挑選圖片。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#E1E0DE" > <RelativeLayout android:id="@+id/headview" android:layout_width="fill_parent" android:layout_height="45dp" android:background="@drawable/plugin_camera_title_bar" android:gravity="center_vertical" android:layout_marginBottom="3dp" > <Button android:layout_width="60dp" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="#fff" android:id="@+id/back" android:text="相冊" android:background="@drawable/plugin_camera_title_btn_back" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_centerVertical="true" /> <Button android:layout_width="67dp" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="#fff" android:id="@+id/cancel" android:text="取消" android:background="@drawable/plugin_camera_title_btn_cancel" android:layout_centerVertical="true" android:layout_marginRight="5dp" android:layout_alignParentRight="true" /> </RelativeLayout> <RelativeLayout android:id="@+id/bottom_layout" android:layout_width="match_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" android:background="@drawable/plugin_camera_bottom_bar" android:layout_marginTop="3dp" > <Button android:id="@+id/preview" android:layout_width="90dp" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:text="預覽" android:background="@drawable/plugin_camera_title_btn_preview" /> <Button android:id="@+id/ok_button" android:layout_width="90dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:layout_marginRight="10dp" android:background="@drawable/plugin_camera_ok_btn_state" /> </RelativeLayout> <GridView android:id="@+id/myGrid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/bottom_layout" android:layout_below="@id/headview" android:layout_centerInParent="true" android:layout_marginTop="2dp" android:horizontalSpacing="10dp" android:numColumns="4" android:verticalSpacing="10dp" android:background="#E1E0DE" /> <TextView android:id="@+id/myText" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="相冊沒有圖片" android:textColor="@color/black" /> </RelativeLayout>
同樣採用 GridView,取得手機中的圖片後加入陣列並顯示。
這裡用到了一個 AlbumHelper(相冊輔助類),是從網路上找到的程式碼,覺得寫得相當不錯。
public List<ImageBucket> getImagesBucketList(boolean refresh) { if (refresh || (!refresh && !hasBuildImagesBucketList)) { buildImagesBucketList(); } List<ImageBucket> tmpList = new ArrayList<ImageBucket>(); Iterator<Entry<String, ImageBucket>> itr = bucketList.entrySet() .iterator(); while (itr.hasNext()) { Entry<String, ImageBucket> entry = (Entry<String, ImageBucket>) itr .next(); tmpList.add(entry.getValue()); } return tmpList; }
取得資料來源後,接著就是顯示,同樣利用相冊輔助類中的方法。
// 初始化,給一些對象賦值 private void init() { helper = AlbumHelper.getHelper(); helper.init(getApplicationContext()); contentList = helper.getImagesBucketList(false); dataList = new ArrayList<ImageItem>(); for(int i = 0; i<contentList.size(); i++){ dataList.addAll( contentList.get(i).imageList ); } back = (Button) findViewById(R.id.back); cancel = (Button) findViewById(R.id.cancel); cancel.setOnClickListener(new CancelListener()); back.setOnClickListener(new BackListener()); preview = (Button) findViewById(R.id.preview); preview.setOnClickListener(new PreviewListener()); intent = getIntent(); Bundle bundle = intent.getExtras(); gridView = (GridView) findViewById(R.id.myGrid); gridImageAdapter = new AlbumGridViewAdapter(mContext,dataList,Bimp.tempSelectBitmap); gridView.setAdapter(gridImageAdapter); tv = (TextView) findViewById(R.id.myText); gridView.setEmptyView(tv); okButton = (Button) findViewById(R.id.ok_button); okButton.setText("完成"+"(" + Bimp.tempSelectBitmap.size() + "/"+ NeedApplication.picNums+")"); }
gridImageAdapter .setOnItemClickListener(new AlbumGridViewAdapter.OnItemClickListener() { @Override public void onItemClick(final ToggleButton toggleButton, int position, boolean isChecked,Button chooseBt) { if (Bimp.tempSelectBitmap.size() >= NeedApplication.picNums) { toggleButton.setChecked(false); chooseBt.setVisibility(View.GONE); if (!removeOneData(dataList.get(position))) { Toast.makeText(AlbumActivity.this, "超出可選圖片張數", Toast.LENGTH_SHORT).show(); } return; } if (isChecked) { chooseBt.setVisibility(View.VISIBLE); Bimp.tempSelectBitmap.add(dataList.get(position)); okButton.setText("完成"+"(" + Bimp.tempSelectBitmap.size() + "/"+ NeedApplication.picNums+")"); } else { Bimp.tempSelectBitmap.remove(dataList.get(position)); chooseBt.setVisibility(View.GONE); okButton.setText("完成"+"(" + Bimp.tempSelectBitmap.size() + "/"+ NeedApplication.picNums+")"); } isShowOkBt(); } });
點擊圖片後,會將其加入公用陣列,並在項目上顯示已選取狀態。
最後是預覽圖片,透過自訂 ViewPager 實現圖片滑動切換,下面貼兩張截圖:

以上就是本文的全部內容,希望對大家的學習有所幫助。
Android 視圖繪制流程(上):View 的測量機制透解
綜述 View 的繪制流程可以拆成三大步:measure(測量自身尺寸)、layout(確定自己在父容器中的位置)、draw(把自己畫到屏幕上)。三者順序固定、缺一不可—
Android 應用架構搭建實錄:從 MVC 走向 MVP 的分層設計
一、前言:為什麼要重新搭一次框架 Android 團隊普遍規模不大,架構的重要性在很多公司並不明顯;加上開源框架層出不窮,上手一個專案的成本被壓得很低。但這不代表架構不重
Android UI 開發入門:常用控制項與互動範例
在 Android 介面開發中,TextView、Button、EditText、ImageView、ProgressBar、AlertDialog 與 Progress
點九圖(.9.png)的「內容顯示區域」到底在說什麼
點九圖的拉伸區域很好理解,但「顯示內容區域」常讓人一頭霧水。以下用一個具體例子把它講清楚。 先說 .9.png 是什麼 .9 是 Android 平台特有的一種圖片格式