Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在android中更改选定的gridview单元格背景?_Android_Gridview_Android Asynctask_Android Image - Fatal编程技术网

在android中更改选定的gridview单元格背景?

在android中更改选定的gridview单元格背景?,android,gridview,android-asynctask,android-image,Android,Gridview,Android Asynctask,Android Image,当用户选择gridview项目时,我想更改gridview项目的背景色?让用户了解他/她选择的图像,请帮助我…提前感谢 public class Gallery extends Activity implements OnItemClickListener { private GridView sdcardImages; ArrayList<String> IPath = new ArrayList<String>(); Stri

当用户选择gridview项目时,我想更改gridview项目的背景色?让用户了解他/她选择的图像,请帮助我…提前感谢

public class Gallery extends Activity implements
        OnItemClickListener {

    private GridView sdcardImages;
    ArrayList<String> IPath = new ArrayList<String>();
    String imagePath;
    private ImageAdapter imageAdapter;
     GridView grid = sdcardImages;
    private Display display;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      try{
          // Request progress bar
          requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
          setContentView(R.layout.gallery);
          Button selpic = (Button) findViewById(R.id.gallery);
          display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

          setupViews();
          setProgressBarIndeterminateVisibility(true);
          loadImages();
       /*   sdcardImages.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

              public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                             int position, long arg3) {
                  try{
//sdcardImages.setBackground(position);

                      int columnIndex = 0;
                      String[] projection = {MediaStore.Images.Media.DATA};
                      Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                              projection,
                              null,
                              null,
                              null);
                      if (cursor != null) {
                          columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                          cursor.moveToPosition(position);
                          imagePath = cursor.getString(columnIndex);
                      }
                      if(IPath.contains(imagePath))
                      {

                              Toast.makeText(getApplicationContext(),"Removed",Toast.LENGTH_SHORT).show();
                          IPath.remove(imagePath);
                          Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
                      }
                      else{
                              Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
                          IPath.add(imagePath);
                          Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
                          }
                  }
                  catch (Exception e)
                  {
                      Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                  }

                  //Toast.makeText(MainActivity.this, "LONG PRESS", Toast.LENGTH_SHORT).show();
                  //set the image as wallpaper
                  return true;
              }
          });*/
          selpic.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                 try{
                     Intent intentMessage = new Intent(Gallery.this,
                             GalleryUpload.class);
                     intentMessage.putStringArrayListExtra("IMAGE", IPath);
                     startActivity(intentMessage);
                 }
                 catch (Exception e)
                 {
                     e.printStackTrace();
                     Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                 }
              }
          });
      }
      catch (Exception e)
      {
          e.printStackTrace();
          Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
      }
    }

    /**
     * Free up bitmap related resources.
     */
    protected void onDestroy() {
        super.onDestroy();

        final int count = grid.getChildCount();
        ImageView v = null;
        for (int i = 0; i < count; i++) {
            v = (ImageView) grid.getChildAt(i);
            ((BitmapDrawable) v.getDrawable()).setCallback(null);
        }
    }
    /**
     * Setup the grid view.
     */
    private void setupViews() {
        sdcardImages = (GridView) findViewById(R.id.sdcard);
       // sdcardImages.setNumColumns(display.getWidth()/95);
        sdcardImages.setChoiceMode(2);
        sdcardImages.setClipToPadding(false);
        sdcardImages.setOnItemClickListener(Gallery.this);
        imageAdapter = new ImageAdapter(getApplicationContext());
        sdcardImages.setAdapter(imageAdapter);

    }
    /**
     * Load images.
     */
    private void loadImages() {
        final Object data = getLastNonConfigurationInstance();
        if (data == null) {
            new LoadImagesFromSDCard().execute();
        } else {
            final LoadedImage[] photos = (LoadedImage[]) data;
            if (photos.length == 0) {
                new LoadImagesFromSDCard().execute();
            }
            for (LoadedImage photo : photos) {
                addImage(photo);
            }
        }
    }
    /**
     * Add image(s) to the grid view adapter.
     *
     * @param value Array of LoadedImages references
     */
    private void addImage(LoadedImage... value) {
        for (LoadedImage image : value) {
            imageAdapter.addPhoto(image);
            imageAdapter.notifyDataSetChanged();
        }
    }

    /**
     * Save bitmap images into a list and return that list.
     *
     * @see android.app.Activity#onRetainNonConfigurationInstance()
     */
    @Override
    public Object onRetainNonConfigurationInstance() {
        final GridView grid = sdcardImages;
        final int count = grid.getChildCount();
        final LoadedImage[] list = new LoadedImage[count];

        for (int i = 0; i < count; i++) {
            final ImageView v = (ImageView) grid.getChildAt(i);
            list[i] = new LoadedImage(((BitmapDrawable) v.getDrawable()).getBitmap());
        }

        return list;
    }



    /**
     * Async task for loading the images from the SD card.
     *
     * @author Mihai Fonoage
     *
     */
    class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {

        /**
         * Load images from SD Card in the background, and display each image on the screen.
         *
         * @see android.os.AsyncTask#
         * doInBackground(Params[])
         */
        @Override
        protected Object doInBackground(Object... params) {
            //setProgressBarIndeterminateVisibility(true);
            Bitmap bitmap = null;
            Bitmap newBitmap = null;
            Uri uri = null;

            // Set up an array of the Thumbnail Image ID column we want
            String[] projection = {MediaStore.Images.Thumbnails._ID};
            // Create the cursor pointing to the SDCard
            Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    projection, // Which columns to return
                    null,       // Return all rows
                    null,
                    null);
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
            int size = cursor.getCount();
            // If size is 0, there are no images on the SD Card.
            if (size == 0) {
                //No Images available, post some message to the user
            }
            int imageID = 0;
            for (int i = 0; i < size; i++) {
                cursor.moveToPosition(i);
                imageID = cursor.getInt(columnIndex);
                uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
                try {
                    bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                    if (bitmap != null) {
                        newBitmap = Bitmap.createScaledBitmap(bitmap, 150,150, true);
                        bitmap.recycle();
                        if (newBitmap != null) {
                            publishProgress(new LoadedImage(newBitmap));
                        }
                    }

                } catch (IOException e) {
                    //Error fetching image, try to recover
                }
            }
            cursor.close();
            return null;
        }
        /**
         * Add a new LoadedImage in the images grid.
         *
         * @param value The image.
         */
        @Override
        public void onProgressUpdate(LoadedImage... value) {
            addImage(value);
        }
        /**
         * Set the visibility of the progress bar to false.
         *
         * @see android.os.AsyncTask#onPostExecute(Object)
         */
        @Override
        protected void onPostExecute(Object result) {
            setProgressBarIndeterminateVisibility(false);
        }
    }
    /**
     * Adapter for our image files.
     * @author Mihai Fonoage
     */
    class ImageAdapter extends BaseAdapter {

        private Context mContext;
        private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();

        public ImageAdapter(Context context) {
            mContext = context;
        }

        public void addPhoto(LoadedImage photo) {
            photos.add(photo);
        }

        public int getCount() {
            return photos.size();
        }

        public Object getItem(int position) {
            return photos.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {

            final ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(mContext);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setPadding(1, 1, 1, 1);
            imageView.setImageBitmap(photos.get(position).getBitmap());

            return imageView;
        }
    }

    /**
     * A LoadedImage contains the Bitmap loaded for the image.
     */
    private static class LoadedImage {
        Bitmap mBitmap;

        LoadedImage(Bitmap bitmap) {
            mBitmap = bitmap;
        }

        public Bitmap getBitmap() {
            return mBitmap;
        }
    }
    /**
     * When an image is clicked, load that image as a puzzle.
     */
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

        try{
//sdcardImages.setBackground(position);

            int columnIndex = 0;
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                    projection,
                    null,
                    null,
                    null);
            if (cursor != null) {
                columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToPosition(position);
                imagePath = cursor.getString(columnIndex);
            }
            if(IPath.contains(imagePath))
            {

                Toast.makeText(getApplicationContext(),"Removed",Toast.LENGTH_SHORT).show();
                IPath.remove(imagePath);
                //Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
            }
            else{


                Toast.makeText(getApplicationContext(),"Selected",Toast.LENGTH_SHORT).show();
                IPath.add(imagePath);
                //Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
System.gc();
    }

}
public类库扩展活动实现
麦克利克监听器{
私有GridView sdcardImages;
ArrayList IPath=新的ArrayList();
字符串图像路径;
专用图像适配器;
GridView网格=SDCardImage;
私人显示器;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
试一试{
//请求进度条
requestWindowFeature(Window.FEATURE\u不确定\u进度);
setContentView(R.layout.gallery);
按钮selpic=(按钮)findViewById(R.id.gallery);
显示=((WindowManager)getSystemService(Context.WINDOW_服务)).getDefaultDisplay();
setupview();
SetProgressBarInDeterminateVibility(真);
loadImages();
/*sdcardImages.setOnItemLongClickListener(新的AdapterView.OnItemLongClickListener(){
长单击(AdapterView arg0、视图arg1、,
整数位置,长arg3){
试一试{
//sdcardImages.后退(位置);
int columnIndex=0;
字符串[]投影={MediaStore.Images.Media.DATA};
Cursor Cursor=managedQuery(MediaStore.Images.Thumbnails.EXTERNAL\u CONTENT\u URI,
投影,
无效的
无效的
无效);
如果(光标!=null){
columnIndex=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
光标。移动位置(位置);
imagePath=cursor.getString(columnIndex);
}
if(IPath.contains(imagePath))
{
Toast.makeText(getApplicationContext(),“已删除”,Toast.LENGTH_SHORT.show();
IPath.remove(imagePath);
Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
}
否则{
Toast.makeText(getApplicationContext(),“Selected”,Toast.LENGTH_SHORT.show();
添加(imagePath);
Toast.makeText(getApplicationContext(),IPath.toString(),Toast.LENGTH_SHORT).show();
}
}
捕获(例外e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
//Toast.makeText(MainActivity.this,“长按”,Toast.LENGTH_SHORT.show();
//将图像设置为壁纸
返回true;
}
});*/
selpic.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
试一试{
意向意向消息=新意向(Gallery.this,
GalleryUpload.class);
intentMessage.putStringArrayListExtra(“图像”,IPath);
开始触觉(意向信息);
}
捕获(例外e)
{
e、 printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
捕获(例外e)
{
e、 printStackTrace();
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
/**
*释放位图相关资源。
*/
受保护的空onDestroy(){
super.ondestory();
final int count=grid.getChildCount();
ImageView v=null;
for(int i=0;i<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/insidepage1"
    android:weightSum="1">


    <GridView
        android:id="@+id/sdcard"
        android:layout_width="fill_parent"
        android:layout_height="438dp"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
        android:numColumns="2"
        android:choiceMode="multipleChoice"
        android:listSelector="@drawable/grid_selector"
        android:layout_weight="1.22" />
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Selected Images"
            android:layout_marginTop="5dp"
            android:id="@+id/gallery" />

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/pressedback" />
    <item android:state_focused="true" android:drawable="@drawable/pressedback" />
    <item android:state_selected="true" android:drawable="@drawable/pressedback" />
    <item android:state_checked="true" android:drawable="@drawable/pressedback" />
    <item android:state_activated="true" android:drawable="@drawable/pressedback" />
    <item android:state_active="true" android:drawable="@drawable/pressedback" />
    <item android:state_long_pressable="true" android:drawable="@drawable/pressedback" />


</selector>
** <LinearLayout
            android:id="@+id/front"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="4dp"
            android:background="@color/white"
            android:orientation="vertical"
            android:paddingBottom="2dp" >



                <ImageView
                    android:id="@+id/profileImage"
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="10dp
                    android:contentDescription="@string/app_name"
                   />
</ImageView>
</LinearLayout>**

I Hope it will help to you...
public class SearchProfileGridAdapter extends BaseAdapter {

    private Context context;
    private LayoutInflater inflator;
    private ArrayList<String> descriptionContent;
    public static boolean btnDoubleClickGridFlag = false;

    public SearchProfileGridAdapter(Context context,ArrayList<String> descriptionContent,String from) {
        this.context = context;
        inflator = LayoutInflater.from(context);
        this.from=from;
        listener=this;

    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        String des="";
        if (convertView == null) {
            convertView = inflator.inflate(R.layout.grid_item,parent,false);
            holder = new ViewHolder();

            holder.person_shortlist=(ImageView)convertView.findViewById(R.id.person_shortlist);


            convertView.setTag(holder);

        }else
        {

            holder = (ViewHolder) convertView.getTag();

        }

    holder.person_shortlist.setBackGround()//TODO
}
private static class ViewHolder {
        private ImageView person_shortlist;
    }