MrStuff88 MrStuff88 - 1 year ago 85
Android Question

Wrong image from

I have

GridView
with images from
drawable
. When I click any image it opens always 1st element from array, not certain clicked element. Whats wrong with my code? Have you any ideas? Thank you!
What happened when I click any image:

private GridView.OnItemClickListener gridviewOnItemClickListener = new GridView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),
FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
};



There is my FullImageActivity


public class FullImageActivity extends AppCompatActivity {

ImageView imageView;
ViewPager viewPager;
SlideImageAdapter adapter;
MainActivity mainActivity;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
getMyIntent();
}

private void getMyIntent(){
Intent intent = getIntent();
int position = intent.getExtras().getInt("id");
viewPager = (ViewPager) findViewById(R.id.myViewPager);
adapter = new SlideImageAdapter(this, position);
viewPager.setAdapter(adapter);
}



There is my SlideImageAdapter


public class SlideImageAdapter extends PagerAdapter {

private Context mContext;
private LayoutInflater layoutInflater;
int number;

public SlideImageAdapter(Context mContext, int number){

this.mContext = mContext;
this.number = number;
}

@Override
public int getCount() {
return MainActivity.mThumbIds.length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {


layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.swipe_layout, container, false);
ImageView imageView = (ImageView) item_view.findViewById(R.id.full_image_view);

imageView.setImageResource(MainActivity.mThumbIds[position]);

container.addView(item_view);


return item_view;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {

container.removeView((LinearLayout)object);
}
}

Answer Source

call:

 viewPager.setCurrentItem(position);

after:

 viewPager.setAdapter(adapter);

you are fetching the position, and sending it to the adapter, but you are not using it. once the adapter is set, you can manually set the position.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download