Remove selected item from GridView - android

Is there any way to remove selected item from gridview.
I want to delete the selected item from my gridview.
I did not find any thing . my code is
public class ImageAdapter extends BaseAdapter{
Context context;
public ImageAdapter(Context context)
{
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 5, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
public Integer[] mThumbIds = {
R.drawable.sample_1,R.drawable.sample_2,R.drawable.sample_3,
R.drawable.sample_3,R.drawable.sample_1,R.drawable.sample_2,
R.drawable.sample_2,R.drawable.sample_3,R.drawable.sample_1
};
}
//////////////////
public class ImageActivity extends Activity {
ImageAdapter iAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
iAdapter = new ImageAdapter(this);
final GridView gView = (GridView)findViewById(R.id.grid_view);
gView.setAdapter(iAdapter);
gView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//gView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// gView.setItemChecked(position, true);
Toast.makeText(ImageActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
iAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.menu_delete)
{
Toast.makeText(this, "Delete",Toast.LENGTH_SHORT ).show();
}
return super.onOptionsItemSelected(item);
}
}
can anyone have idea .
thank

you are using a table :
public Integer[] mThumbIds = {
R.drawable.sample_1,R.drawable.sample_2,R.drawable.sample_3,
R.drawable.sample_3,R.drawable.sample_1,R.drawable.sample_2,
R.drawable.sample_2,R.drawable.sample_3,R.drawable.sample_1}
Tables are not modifiable.
Replace it by a List on which you will be able to make add or remove operations. Simply call notifyDataSetChanged when a change is made to let the adapter know that its list has been modified.

As Teovald and pskink suggested, you cannot have a fixed list of images and then implement the remove functionality that you are looking for. If you want to add remove, change your design and make sure your data set is also removable. What you have tried so far seems to be using some really basic code which is good to show basic GridView feature.
Just try this. Create a image data set class which returns the actual images. Store the images in a List that can be modified. Add setters/getters to this data set and also add a method to delete a particular item. Change your image adapter to use the image from this new data set. Whenever an image is deleted, call the notifyDataSetChanged on the adpater.
Good luck

Related

Adding default view in listview in android

I'm using a listview in my android application in which the listitems(in my case it is bitmap images) are loaded dynamically. Actually i'm creating the bitmap images and then it is loaded one by one into the list. what i want is to show all the list items with some default image and update them correspondingly when the bitmap image is created. My code is given below,
public class BitmapDemoActivity extends Activity {
HorizontalListView listview;
Vector<Bitmap> thumbImg;
BitmapCreator creator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listviewdemo);
creator=new BitmapCreator();
thumbImg= new Vector<Bitmap>(97);
listview = (HorizontalListView)findViewById(R.id.listview);
listview.setAdapter(new BitmapAdapter());
new AsyncBitmapCreate().execute();
}
private class AsyncBitmapCreate extends AsyncTask<Void, Bitmap, Void>{
//Bitmap[] temp=new Bitmap[44];
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
for(int i=0;i<97;i++){
publishProgress(creator.generateBitmap(i+1));
}
return null;
}
#Override
protected void onProgressUpdate(Bitmap... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
new BitmapAdapter().add(values[0]);
new BitmapAdapter().notifyDataSetChanged();
}
}
class BitmapAdapter extends BaseAdapter{
public void add(Bitmap bitmap)
{
Log.w("My adapter","add");
thumbImg.add(bitmap);
}
#Override
public int getCount() {
return thumbImg.capacity();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View retval = inflater.inflate(R.layout.listitem, null);
ImageView img = (ImageView) retval.findViewById(R.id.tImage);
img.setImageBitmap(thumbImg.get(position));
return retval;
}
};
}
Here i'm using a vector in which after creating each bitmap, it is inserted into that vector. I'm using an asynctask to create the bitmap. After each bitmap is created i'm calling notifydatasetchanged() method to update the listview. But now in the output whenever each bitmap image is created it is adding one item in the listview with that image. But my requirement is to show all the 97 items in my list with some default image and whenever bitmap is created update the corresponding listitem.
can anyone help me?? Thanks in advance....
The simplest would be to include the default image as the src for the ImageView with id tImage in your layout listitem.xml. And in your getView method, replace the default image if the Bitmap for that position is available.
ImageView img = (ImageView) retval.findViewById(R.id.tImage);
Bitmap bmp = null;
if(position < thumbImg.size()){
thumbImg.get(position);
}
if(null != bmp){
img.setImageBitmap(bmp);
}

screen rotation and live update gridview android

i have a big doubt about memory leak and screen rotation. I know that activity is destroy when that happens and new one is started. With my code, with is the best way to show the gridview? (this activity is part of a tab activity so in the main one i get the pictures from web services and put them on the object, using AsyncTask)
i would like to show the pictures at the same time they are saved on the object. Like simulating ajax...is that possible? at the moment, they are all show on the start or resume.
Also, im facing memory leak here?
last question, how can i show photos in the grid
my code:
public class LoteFotosActivity extends Activity {
Sistema sis=Sistema.getInstance();
Lote lote;
GridView gridview;
ImageAdapter iA;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lote_foto_view);
Bundle extras = getIntent().getExtras();
lote=sis.getLoteDetalle(extras.getInt("LoteID"));
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(iA=new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(LoteFotosActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return lote.FOTOS.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200,200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(lote.FOTOS.get(position));
return imageView;
}
}
//test looking
public void onResume() {
super.onResume();
Toast.makeText(this,"ON RESUME",
Toast.LENGTH_SHORT).show();
// gridview.setAdapter(new ImageAdapter(this));
// foto.setImageDrawable(lote.FOTOS.get(0));
}
public void onPause() {
super.onPause();
Toast.makeText(this,"onPause",
Toast.LENGTH_SHORT).show();
iA=null;
gridview.setAdapter(iA=new ImageAdapter(this));
// foto.setImageDrawable(lote.FOTOS.get(0));
}
thx in advance !
I think you should add this to your activity
android:configChanges="orientation"
to avoid the destroying problem when rotating the screen... with this you dont need to save state to restore, there is no need because the activity is not destroyed and recreated everytime the screen rotation changes
For API 13+ the screenSize must also be handled:
android:configChanges="orientation|screenSize"

Constructing Dynamic List View In Android

Iam trying to create a list view dynamically, Please provide me an example for list view in android...
Activity class......
public class UsersListActivity extends ListActivity{
RegisterUser registerUser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = getListOfAllUsers();
Toast.makeText(getApplicationContext(),
"States Array lentgh is : " + statesList.length,
Toast.LENGTH_LONG).show();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}}
and create an xml file named list_item.xml and paste the below code.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="#drawable/border_cell">
</TextView>
You can create your own List View by extending Base adapter class
public class ListAdapterDroidman extends BaseAdapter{
private ArrayList<ListitemDroidman> list = new ArrayList<ListitemDroidman>();
#SuppressWarnings("unused")
private Context context;
public ListAdapterDroidman(Context context) {
this.context = context;
}
public void addItem(ListitemDroidman item) {
list.add(item);
}
public void addItem(ListitemDroidman item,int pos)
{
list.add(pos, item);
}
public void removeItem(int pos)
{
list.remove(pos);
}
public void clearList()
{
list.clear();
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return list.get(position);
}
}
Then create your own layout
public class ListitemDroidman extends LinearLayout {
TextView filename;
ImageView iv;
public ListitemDroidman(Context context) {
super(context);
}
public void setInfo(Context context, Bitmap icon, String fname,int colorId) {
iv=new ImageView(context);
iv.setImageBitmap(icon);
iv.setPadding(0, 0, 20, 0);
addView(iv);
filename = new TextView(context);
filename.setTextSize(20);
filename.setTextColor(getResources().getColor(colorId));
filename.setText(fname);
addView(filename);
}
}
Now create listitems in your activityClass
create object of the adapter that u have created
myListitem = new ListitemDroidman(this);
icon = BitmapFactory.decodeResource(getResources(),
R.drawable.folder_icon);
myListitem.setInfo(getApplicationContext(), icon, filelist[i],
R.color.color_white);
add the listitem to the adaper as in normal list
la_file.addItem(myListitem);
Try this tutorial to understand how to use ListView.
http://developer.android.com/resources/tutorials/views/hello-listview.html
Why don't you just take a look at the ApiDemos of your android SDK..
You can find 14 examples of ListActivities implementations..
Or just search here or on Google, you can find lots of examples
Then if you want to achieve something in particular you can ask a more specific question here, does it sound fair?

How to create a Photo Gallery on Android?

I want to create a photo gallery on Android. I'm using Gallery and BaseAdapter to create a scrollable gallery. Now I want to add an action when an image of the gallery is shown (each image's width is the same as screen width), so I need to get its index in the image array. My question is how to get the index of the image which shows on the screen?
I want to get the index of the image as soon as it shows on the screen, not on click event.
I've tried to get current image position in getView(), but the result is strange:
I scroll to image02 but position=2 (should be 1). When I scroll back, image02's position=0 (should be 1).
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) this.findViewById(R.id.Gallery);
g.setAdapter(new ImageAdapter(this));
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] mImageIds = {
//each image's size is 320x60
R.drawable.btm01,
R.drawable.btm02,
R.drawable.btm03
};
public ImageAdapter(Context c){
this.mContext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mImageIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(320,60));
return imageView;
}
Check this example.
// Reference the Gallery view
Gallery g = (Gallery) this.findViewById(R.id.Gallery);
// Set the adapter to our custom adapter (below)
g.setAdapter(new ImageAdapter(this));
// Set a item click listener, and just Toast the clicked position
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(Gallery1.this, "" + position, Toast.LENGTH_SHORT).show();
}
});

Android: Programmatically animate between images in Gallery widget

Note: As of Jellybean the gallery widget is deprecated. A ViewPager should be used instead.
I'd like to programmatically move between images in the Gallery widget, with animation.
I can change the currently displaying image using the setSelection(int position) method, however that does not animate. Then there's setSelection(int position, bool animate) but the extra boolean on the end there doesn't appear to do anything.
In the source of Gallery it appears that it can handle DPAD key-presses, so a work-around I thought of was to fake the key-presses. Eg.
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT))
However I can't get this working for some reason. Anyone tried this?
I notice three of the widget's methods I'd love to use moveNext(), movePrevious() and scrollToChild() are all private and unusable.
Does anyone know how I might be able to do this?
Just call the key press handler for the gallery directly:
public boolean onKeyDown(int keyCode, KeyEvent event)
i.e
Gallery gallery = ((Gallery) findViewById(R.id.gallery));
gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, new KeyEvent(0, 0));
One important thing - this solution works only if child that is on left/right was already created, which means that it has to be 'visible'. If you have your image on fullscreen - consider setting spacing to -1 value.
You can Animate using dispatchKeyEvent or calling onFling directly.
Here is sample code for dispatchKeyEvent:
KeyEvent evtKey = new KeyEvent(0, KeyEvent.KEYCODE_DPAD_RIGHT);
dispatchKeyEvent(evtKey);
Use gallery.setSelected(int); Here is a simple example.
public class Splash extends Activity {
ArrayList objects = new ArrayList();
Gallery g;
int i = 0;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.photos);
g = (Gallery) findViewById(R.id.gallery);
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
objects.add(getResources().getDrawable(R.drawable.icon));
g.setAdapter(new CustomAdapter(this, objects));
g.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView arg0, View arg1,
int arg2, long arg3) {
Log.i("", "selected " + arg2);
}
#Override
public void onNothingSelected(AdapterView arg0) {}
});
}
#Override
public void onBackPressed() {
g.setSelection(i++);
}
private class CustomAdapter extends BaseAdapter {
private Context mCtx;
private List objects;
public int getCount() {
return this.objects.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public CustomAdapter(Context context, ArrayList objects) {
super();
mCtx = context;
this.objects = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView row = (ImageView) convertView;
if (row == null) {
row = new ImageView(mCtx);
row.setBackgroundDrawable(objects.get(position));
}
return row;
}
}
}
In the end I wrote my own version of the Gallery widget with the help of the code at this site.
I then wrote my own method which uses mFlingRunnable.startUsingDistance(distance);
Now I can programmatically animate the gallery between images.
Try this
mGallery.onFling(null,null, velocity,0);
http://groups.google.com/group/android-developers/browse_thread/thread/9140fd6af3061cdf#

Categories

Resources