I have a GridView that uses an adapter to set ImageViews and when I open up an AlertDialog and focus on its TextView, the images in the GridView shift positions. How do I stop that from happening?
import android.content.Context;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ImageAdapter extends BaseAdapter {
private Context context;
private String[] directory;
public ImageAdapter(Context c, String[] d) {
this.context = c;
this.directory = d;
}
public int getCount() {
return directory.length;
}
public Object getItem(int position) {
return directory[position];
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
View v;
if (convertView == null) { // if it's not recycled, initialize some attributes
LayoutInflater li = LayoutInflater.from(context);
v = li.inflate(R.layout.iblock, null);
ImageView iv = (ImageView)v.findViewById(R.id.foodImage);
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 2;
iv.setImageBitmap(BitmapFactory.decodeFile(directory[position], bfo));
TextView tv = (TextView)v.findViewById(R.id.foodName);
String[] s = directory[position].split("[\\/.]+");
} else {
v = convertView;
}
return v;
}
}
protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_SEARCH_ID:
LayoutInflater factory = LayoutInflater.from(this);
View searchView = factory.inflate(R.layout.searchbar2, null);
final EditText searchfield = (EditText) searchView.findViewById(R.id.searchfield);
ImageButton ib = (ImageButton) searchView.findViewById(R.id.searchbutton);
ib.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), SearchResults.class);
i.putExtra("query", searchfield.getText().toString());
startActivity(i);
}
});
AlertDialog ad = new AlertDialog.Builder(SearchResults.this)
.setView(searchView)
.create();
Window win = ad.getWindow();
win.setGravity(48);
return ad;
}
return null;
}
Your
Viewrecycling is broken. When you are given aViewto recycle, you still need to bind your data to it (in this case, putting the image in theImageView). The only part you can skip when recycling aViewis inflating the layout.