Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android listView 子控件事件錯行處理

android listView 子控件事件錯行處理

編輯:關於Android編程

package com.tailan.moms.adapter;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import com.tailan.moms.activity.ApplicationActivity;
import com.tailan.moms.activity.HiddenDangeActivity;
import com.tailan.moms.activity.PictureViewActivity;
import com.tailan.moms.activity.R;
import com.tailan.moms.activity.workorder.WorkOrderReportActivity;
import com.tailan.moms.common.Communal;
import com.tailan.moms.model.PatrolListData;
import com.tailan.moms.model.PatrolReportBackData;
import com.tailan.moms.model.TaskTemplateDetail;
import com.tailan.moms.tools.LogFile;
import com.tailan.moms.tools.MyGridView;


import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;


public class PatrolAdapter extends BaseAdapter {


private List<TaskTemplateDetail> list = null;
private LayoutInflater inflater;
private Context context = null;
List<PatrolReportBackData> patrolReportBackDatas = null;
public static final int NONE = 0;
public static final int PHOTOHRAPH = 1;// 拍照
public static final int PHOTOZOOM = 2; // 縮放
public static final int PHOTORESOULT = 3;// 結果
public static final String IMAGE_UNSPECIFIED = "image/*";
byte[] bitmapBytes = new byte[1024];
protected String bitPhoto = "";
ApplicationActivity activity;
protected ArrayList<HashMap<String, Object>> imageItem = null;
int index = -1;
protected MyGridView photograph = null;
List<ViewHolderData> holderDatas = null;
//PatrolReportBackData patrolReportBackData = null;
int viewIndex = 0;
boolean changed = true;
public PatrolAdapter(List<TaskTemplateDetail> list,Context context,List<PatrolReportBackData> patrolReportBackDatas,ApplicationActivity activity)
{
this.list = list;
this.context = context;
this.inflater = LayoutInflater.from(context);
this.patrolReportBackDatas = patrolReportBackDatas;
this.activity = activity;
imageItem = new ArrayList<HashMap<String, Object>>();
holderDatas = new ArrayList<ViewHolderData>();

for (int i = 0; i < patrolReportBackDatas.size(); i++) {
String isNormal = patrolReportBackDatas.get(i).getIsNormal();
if(isNormal != null)
{
bitPhoto = patrolReportBackDatas.get(i).getPhotos();
ViewHolderData viewHolderData = new ViewHolderData();
viewHolderData.setPosition(i);
if(isNormal.equals("0"))
viewHolderData.setSpinnerIndex(2);
else if(isNormal.equals("1"))
viewHolderData.setSpinnerIndex(1);
 
viewHolderData.setDescription(patrolReportBackDatas.get(i).getFinishDesc());
viewHolderData.setStrBitPhoto(bitPhoto);
 
       if(bitPhoto != null)
{
         imageItem = new ArrayList<HashMap<String, Object>>();
String[] strImage = bitPhoto.split(",");
for (String string : strImage) {
if(!string.equals(""))
{
Communal.getInstance().saveImage(context, string);
String imagepath = Environment.getExternalStorageDirectory()  + "/MOMSPHOTO/" + Communal.getInstance().getImageName();
       BitmapFactory.Options opts = new BitmapFactory.Options();
       opts.inJustDecodeBounds =  true ;
       BitmapFactory.decodeFile(imagepath, opts);
       opts.inSampleSize = computeSampleSize(opts, - 1 ,  80 * 80 );
       opts.inJustDecodeBounds =  false ;
       try  {
            Bitmap bmp = BitmapFactory.decodeFile(imagepath, opts);
            HashMap<String, Object> hashmap = new HashMap<String, Object>(); 
hashmap.put("ItemImage", bmp);//添加圖像資源的ID  
hashmap.put("ItemText", Communal.getInstance().getImageName());//按序號做ItemText 
   imageItem.add(hashmap);
  
            }  catch  (OutOfMemoryError err) {

            }
}
}

viewHolderData.setImageList(imageItem);
}
      
       holderDatas.add(viewHolderData);
}
}

}

@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}


@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}


@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}


//private  List<ViewHolder> holder = new ArrayList<ViewHolder>();
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.i("索引值:", String.valueOf(position));
//final PatrolReportBackData patrolReportBackData = patrolReportBackDatas.get(position);
// viewIndex = position;
index = position;

final ViewHolder viewHolder;
   if (convertView == null) {
       convertView = inflater.inflate(R.layout.item_list_patrol, null);
       viewHolder = new ViewHolder();
       viewHolder.id = (TextView)convertView.findViewById(R.id.item_patrol_id_textView);
       viewHolder.name = (TextView)convertView.findViewById(R.id.item_patrol_name_textView);
       viewHolder.spinner = (Spinner)convertView.findViewById(R.id.item_patrol_whetherAnomaly);
       viewHolder.relativeLayout = (RelativeLayout)convertView.findViewById(R.id.item_relativeLayout_patrol_description);
       viewHolder.disposeDescription = (EditText)convertView.findViewById(R.id.item_patrol_disposeDescription);
       viewHolder.addPicture = (TextView)convertView.findViewById(R.id.item_patrol_addPicture);
       viewHolder.photograph = (MyGridView)convertView.findViewById(R.id.item_patrol_photograph);
      
       viewHolder.spinner.setTag(position);
       viewHolder.disposeDescription.setTag(position);
       viewHolder.addPicture.setTag(position);
       viewHolder.photograph.setTag(position);
      
       viewHolder.spinner.setOnTouchListener(new OnTouchListener() {


           public boolean onTouch(View view, MotionEvent event) {


                   // 在TOUCH的UP事件中,要保存當前的行下標,因為彈出軟鍵盤後,整個畫面會被重畫


                   // 在getView方法的最後,要根據index和當前的行下標手動為EditText設置焦點


                   if(event.getAction() == MotionEvent.ACTION_UP) {


                           index= Integer.parseInt(view.getTag().toString());
                           //patrolReportBackData = patrolReportBackDatas.get(index);
                   }
                   return false;
           }
   });
  
   viewHolder.disposeDescription.setOnTouchListener(new OnTouchListener() {


           public boolean onTouch(View view, MotionEvent event) {


                   // 在TOUCH的UP事件中,要保存當前的行下標,因為彈出軟鍵盤後,整個畫面會被重畫


                   // 在getView方法的最後,要根據index和當前的行下標手動為EditText設置焦點


                   if(event.getAction() == MotionEvent.ACTION_UP) {


                  
index= Integer.parseInt(view.getTag().toString());
                  
//patrolReportBackData = patrolReportBackDatas.get(index);
                   }
                   return false;
           }
   });
  
   viewHolder.addPicture.setOnTouchListener(new OnTouchListener() {


           public boolean onTouch(View view, MotionEvent event) {


                   // 在TOUCH的UP事件中,要保存當前的行下標,因為彈出軟鍵盤後,整個畫面會被重畫


                   // 在getView方法的最後,要根據index和當前的行下標手動為EditText設置焦點


                   if(event.getAction() == MotionEvent.ACTION_UP) {


                           index= Integer.parseInt(view.getTag().toString());
//                            patrolReportBackData = patrolReportBackDatas.get(index);
//                            if(patrolReportBackData.getPhotos() != null)
//                           
bitPhoto = patrolReportBackData.getPhotos();
//                            else
//                           
bitPhoto = "";
                           PatrolReportBackData patrolReportBackData = patrolReportBackDatas.get(index);
                           if(patrolReportBackData.getPhotos() != null)
                          
bitPhoto = patrolReportBackData.getPhotos();
                           else
                          
bitPhoto = "";
                           if(holderDatas.get(index).getImageList() != null)
                          
imageItem = holderDatas.get(index).getImageList();
                           else
                          
imageItem = new ArrayList<HashMap<String,Object>>();
                   }
                   return false;
           }
   });
  
   viewHolder.photograph.setOnTouchListener(new OnTouchListener() {


           public boolean onTouch(View view, MotionEvent event) {


                   // 在TOUCH的UP事件中,要保存當前的行下標,因為彈出軟鍵盤後,整個畫面會被重畫


                   // 在getView方法的最後,要根據index和當前的行下標手動為EditText設置焦點


                   if(event.getAction() == MotionEvent.ACTION_UP) {


                           index= Integer.parseInt(view.getTag().toString());
                           //patrolReportBackData = patrolReportBackDatas.get(index);
                   }
                   return false;
           }
   });
   
    viewHolder.disposeDescription.clearFocus();


       if(index!= -1 && index == position) {


              // 如果當前的行下標和點擊事件中保存的index一致,手動為EditText設置焦點。


         viewHolder.disposeDescription.requestFocus();


       }

      
       convertView.setTag(viewHolder);
   } else {
    viewHolder = (ViewHolder) convertView.getTag();
    changed = false;
    viewHolder.id.setText("");
    viewHolder.id.setTag(null);
    viewHolder.spinner.setSelection(0);
       /**************************************/
//        boolean isNewSpinner = false;
//        for (ViewHolderData holderData : holderDatas) {
// if(holderData.getPosition() == position)
// {
// viewHolder.spinner.setSelection(holderData.getSpinnerIndex());
// isNewSpinner = true;
// }
//        }
//       
//        if(isNewSpinner)
//          viewHolder.spinner.setSelection(0);
       /**************************************/
viewHolder.disposeDescription.setText("");
bitPhoto = "";
imageItem = new ArrayList<HashMap<String,Object>>();
ImageAdapter adapter = new ImageAdapter(imageItem,context);
viewHolder.photograph.setAdapter(adapter);
changed = true;

    viewHolder.spinner.setTag(position);
       viewHolder.disposeDescription.setTag(position);
       viewHolder.addPicture.setTag(position);
       viewHolder.photograph.setTag(position);
   }
  
 
if(list != null)
{
TaskTemplateDetail taskTemplateDetail = list.get(position);
viewHolder.name.setText(taskTemplateDetail.getCheckItem());
viewHolder.id.setText(taskTemplateDetail.getCheckTemplateItemId());
viewHolder.id.setTag(taskTemplateDetail);

 String whether_anomaly = Communal.getInstance().getStirng(context,R.string.whether_anomaly);//是否異常
setSpinnerValue(whether_anomaly.split(","),viewHolder.spinner,"是否異常");
viewHolder.spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
// long selected=arg0.getItemIdAtPosition(arg2);  


ViewGroup.LayoutParams autoSendLayoutParams = null;
switch (arg2) {
case 0:
autoSendLayoutParams = viewHolder.relativeLayout.getLayoutParams();
autoSendLayoutParams.height = 0;
viewHolder.relativeLayout.setLayoutParams(autoSendLayoutParams);

// if(patrolReportBackData != null && changed != false)
// patrolReportBackData.setIsNormal("");//0是正常1是異常

if(holderDatas.size() > index)
{
holderDatas.get(index).setSpinnerIndex(0);
patrolReportBackDatas.get(index).setIsNormal("");
}
break;
case 1:
autoSendLayoutParams = viewHolder.relativeLayout.getLayoutParams();
autoSendLayoutParams.height = 0;
viewHolder.relativeLayout.setLayoutParams(autoSendLayoutParams);

// if(patrolReportBackData != null && changed != false)
// patrolReportBackData.setIsNormal("1");//0是正常1是異常

if(holderDatas.size() > index)
{
holderDatas.get(index).setSpinnerIndex(1);
patrolReportBackDatas.get(index).setIsNormal("1");
}
break;
case 2:
autoSendLayoutParams = viewHolder.relativeLayout.getLayoutParams();
autoSendLayoutParams.height = LayoutParams.WRAP_CONTENT;
viewHolder.relativeLayout.setLayoutParams(autoSendLayoutParams);

// if(patrolReportBackData != null && changed != false)
// patrolReportBackData.setIsNormal("0");//0是正常1是異常

//Log.i("打印出來瞧瞧", String.valueOf(index));
if(holderDatas.size() > index)
{  www.2cto.com
holderDatas.get(index).setSpinnerIndex(2);
patrolReportBackDatas.get(index).setIsNormal("0");
}
break;
default:
break;
}
}


@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}

});

viewHolder.disposeDescription.addTextChangedListener(new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub

if(viewHolder.id.getTag() != null)
{
// if(patrolReportBackData != null && changed != false)
// patrolReportBackData.setFinishDesc(s.toString());

if(holderDatas.size() > index)
{
holderDatas.get(index).setDescription(s.toString());
patrolReportBackDatas.get(index).setFinishDesc(s.toString());
Log.i("文本輸入值:", holderDatas.get(index).getDescription());
Log.i("文本輸入值Index:", String.valueOf(index));
}
}

//viewHolder.disposeDescription.clearFocus();
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub

}

@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub

}
});

viewHolder.addPicture.setOnClickListener(new TextView.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
photograph = viewHolder.photograph;

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(Communal.getInstance().setPhotoName(context)));
activity.startActivityForResult(intent, PHOTOHRAPH);
}
});

 
boolean oldViewData = false;
for (ViewHolderData holderData : holderDatas) {

// if(holderDatas.size() > index)
// Log.i("文本輸入值2:", holderDatas.get(position).getDescription());
if(holderData.getPosition() == position)
{
// if(holderData.getSpinnerIndex() == 2)
// {
// Log.i("比較打印出來瞧瞧", String.valueOf(position));
// Log.i("點擊打印出來瞧瞧", String.valueOf(index));
//
// }

//Log.i("文本輸入值:", holderData.getDescription());
// if(holderDatas.size() > index)
// Log.i("文本輸入值1:", holderDatas.get(position).getDescription());
oldViewData = true;
viewHolder.spinner.setSelection(holderData.getSpinnerIndex(),true);
if(holderData.getDescription() != null)
{
viewHolder.disposeDescription.setText(holderData.getDescription());
}

if(holderData.getImageList() != null)
{
ImageAdapter adapter = new ImageAdapter(holderData.getImageList(),context);
viewHolder.photograph.setAdapter(adapter);
viewHolder.photograph.setOnItemClickListener(pictureView_ItemClickListener); 
}

}
}

if(!oldViewData)
{
if(holderDatas.size() < list.size())
{
ViewHolderData viewHolderData = new ViewHolderData();
//Log.i("添加打印出來瞧瞧", String.valueOf(position));
viewHolderData.setPosition(position);
holderDatas.add(viewHolderData);
}

// if(holderDatas.size() > index)

//    patrolReportBackData = patrolReportBackDatas.get(index);  
    

 

}
}
return convertView;
}

static class ViewHolder {
TextView id;
TextView name;
   Spinner spinner;
   RelativeLayout relativeLayout;
   EditText disposeDescription;
   TextView addPicture;
   MyGridView photograph;
}


static class ViewHolderData {
   String  description;
int spinnerIndex;
   String strBitPhoto;
   ArrayList<HashMap<String, Object>> imageList;
   int position;
  
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getSpinnerIndex() {
return spinnerIndex;
}
public void setSpinnerIndex(int spinnerIndex) {
this.spinnerIndex = spinnerIndex;
}
public String getStrBitPhoto() {
return strBitPhoto;
}
public void setStrBitPhoto(String strBitPhoto) {
this.strBitPhoto = strBitPhoto;
}
public ArrayList<HashMap<String, Object>> getImageList() {
return imageList;
}
public void setImageList(ArrayList<HashMap<String, Object>> imageList) {
this.imageList = imageList;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
  
  
}


public void result(int requestCode, int resultCode, Intent data)
{
String log = "返回值時間:" + Communal.getInstance().getFormatDate("") + "返回值:" + requestCode + "dd" + resultCode + "cc" + data;
LogFile.getInstance().addLog(log);
// 拍照
if (requestCode == PHOTOHRAPH) {
//設置文件保存路徑這裡放在跟目錄下
File picture = Communal.getInstance().getPhotoName();
if(picture != null)
startPhotoZoom(Uri.fromFile(picture));
}

if (data == null)
return;

// 讀取相冊縮放圖片
if (requestCode == PHOTOZOOM) {
startPhotoZoom(data.getData());
}
// 處理結果
if (requestCode == PHOTORESOULT) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = null;
try {
photo = extras.getParcelable("data");
if(photo == null)
return;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)壓縮文件
stream.flush();
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
String log1 = "打印時間:" + Communal.getInstance().getFormatDate("") + "PatrolAdapter異常:" + e.getMessage();
    LogFile.getInstance().addLog(log1);
e.printStackTrace();
}

HashMap<String, Object> map = new HashMap<String, Object>(); 
   map.put("ItemImage", photo);//添加圖像資源的ID  
   map.put("ItemText", Communal.getInstance().getImageName());//按序號做ItemText 
   imageItem.add(map);
   if(holderDatas.size() > index)
        {
    holderDatas.get(index).setImageList(imageItem);
        }
initGridViewImage();
initPicture(Communal.getInstance().getImageName());
}


}


}

public void startPhotoZoom(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
intent.putExtra("crop", "true");
// aspectX aspectY 是寬高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", 64);
intent.putExtra("outputY", 64);
intent.putExtra("return-data", true);
activity.startActivityForResult(intent, PHOTORESOULT);
}

private void initGridViewImage()
{
ImageAdapter adapter = new ImageAdapter(imageItem,context);
photograph.setAdapter(adapter);
photograph.setOnItemClickListener(pictureView_ItemClickListener); 
}
 
GridView.OnItemClickListener pictureView_ItemClickListener = new GridView.OnItemClickListener(){


@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
//在本例中arg2=arg3
  Intent intent = null;
  HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);
           String text = (String)item.get("ItemText");
           intent = new Intent(context,PictureViewActivity.class);
           intent.putExtra("pictureName", text);
           context.startActivity(intent);
          
}};

GridView.OnItemLongClickListener pictureView_ItemLongClickListener = new GridView.OnItemLongClickListener(){


@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("提示");
       builder.setMessage("確認刪除圖片嗎?");
       builder.setIcon(R.drawable.icon);
       builder.setPositiveButton("確認", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int whichButton) {
         if(!bitPhoto.equals("")  || bitPhoto != null)
         {
         String[] bitPhotoStr = bitPhoto.split(",");
         bitPhoto = "";
         for (int i = 0; i < bitPhotoStr.length; i++) {
if(arg2 == i)
continue;
if(bitPhoto.equals("") || bitPhoto == null)
bitPhoto = bitPhotoStr[i];
else
bitPhoto = bitPhoto + "," + bitPhotoStr[i];
}
        
         imageItem.remove(arg2);
         if(holderDatas.size() > index)
         {
         holderDatas.get(index).setImageList(imageItem);
         holderDatas.get(index).setStrBitPhoto(bitPhoto);
         patrolReportBackDatas.get(index).setPhotos(bitPhoto);
//          if(patrolReportBackData != null && changed != false)
//          patrolReportBackData.setPhotos(bitPhoto);
         }
         ImageAdapter adapter = new ImageAdapter(imageItem,context);
         photograph.setAdapter(adapter);
         }
       }
       });
       builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int whichButton) {
        //取消按鈕事件
       }
       });
       builder.show();

return false;
}

 


};

 
private void initPicture(String pictureName) {
// TODO Auto-generated method stub
String imagepath = Environment.getExternalStorageDirectory()  + "/MOMSPHOTO/" + pictureName;
String byte64Str = getImageBinary(imagepath);
if(bitPhoto.equals("") || bitPhoto == null)
bitPhoto = byte64Str;
else
bitPhoto = bitPhoto + "," + byte64Str;
if(holderDatas.size() > index)
{
holderDatas.get(index).setStrBitPhoto(bitPhoto);
patrolReportBackDatas.get(index).setPhotos(bitPhoto);
// if(patrolReportBackData != null && changed != false)
// patrolReportBackData.setPhotos(bitPhoto);
}
}
 
/** 
* 圖片轉換成字符串[BASE64] 
*  
* @return 
*/ 
public String getImageBinary(String path) {  
   System.out.println("path--->" + path);  
     try {  
    
      Bitmap bitmap = getBitmapFromFile(new File(path),640,640);//scalePicture(path,640,640);
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          bitmap.compress(CompressFormat.PNG,100,baos);
          String uploadBuffer = new String(Base64.encodeToString(baos.toByteArray(),Base64.DEFAULT));
          baos.flush();
          baos.close();
          System.out.println("圖片信息轉換成字符串為:---->" + uploadBuffer);
          return uploadBuffer;  
       }
     catch(IOException e)
     {
        String log = "打印時間:" + Communal.getInstance().getFormatDate("") + "ApplincationActivity異常:" + e.getMessage();
LogFile.getInstance().addLog(log);
     e.printStackTrace();
     }
     catch (Exception e) {  
    
String log = "打印時間:" + Communal.getInstance().getFormatDate("") + "ApplincationActivity異常:" + e.getMessage();
LogFile.getInstance().addLog(log);
           e.printStackTrace();  
       }
 
       return null;  
   }  

/***************************************************************************/
public Bitmap getBitmapFromFile(File dst, int width, int height) {
   if (null != dst && dst.exists()) {
       BitmapFactory.Options opts = null;
       if (width > 0 && height > 0) {
           opts = new BitmapFactory.Options();
           opts.inJustDecodeBounds = true;
           BitmapFactory.decodeFile(dst.getPath(), opts);
           // 計算圖片縮放比例
           final int minSideLength = Math.min(width, height);
           opts.inSampleSize = computeSampleSize(opts, minSideLength,
                   width * height);
           opts.inJustDecodeBounds = false;
           opts.inInputShareable = true;
           opts.inPurgeable = true;
       }
       try {
           return BitmapFactory.decodeFile(dst.getPath(), opts);
       } catch (OutOfMemoryError e) {
         String log = "打印時間:" + Communal.getInstance().getFormatDate("") + "ApplincationActivity異常:" + e.getMessage();
LogFile.getInstance().addLog(log);
           e.printStackTrace();
       }
   }
   return null;
}

public static int computeSampleSize(BitmapFactory.Options options,
       int minSideLength, int maxNumOfPixels) {
   int initialSize = computeInitialSampleSize(options, minSideLength,
           maxNumOfPixels);


   int roundedSize;
   if (initialSize <= 8) {
       roundedSize = 1;
       while (roundedSize < initialSize) {
           roundedSize <<= 1;
       }
   } else {
       roundedSize = (initialSize + 7) / 8 * 8;
   }


   return roundedSize;
}


private static int computeInitialSampleSize(BitmapFactory.Options options,
       int minSideLength, int maxNumOfPixels) {
   double w = options.outWidth;
   double h = options.outHeight;


   int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
           .sqrt(w * h / maxNumOfPixels));
   int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math
           .floor(w / minSideLength), Math.floor(h / minSideLength));


   if (upperBound < lowerBound) {
       // return the larger one when there is no overlapping zone.
       return lowerBound;
   }


   if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
       return 1;
   } else if (minSideLength == -1) {
       return lowerBound;
   } else {
       return upperBound;
   }
}
 
private void setSpinnerValue(String[] str,Spinner spinner,String spinnerTitle)
{
//准備一個數組適配器
ArrayAdapter adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item,str);
//設置下拉樣式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//為下拉列表設置適配器
spinner.setAdapter(adapter);
spinner.setPrompt(spinnerTitle);
}


}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved