Saturday, 3 January 2015

ViewPager with Custom PageAdapter, how to use XML file instead of defining layout in java



I'm programming a quartet game, therefore I need a gallery including all the attibutes of each card. I found an example of ViewPager with a custom PagerAdapter: http://ift.tt/1BuBxDQ


For a simple Gallery view this is pretty nice, but I would like to include a XML file (e.g. of my game activity) instead of defining all layout params explicitly. Thanks for any idea!


Here my adapter class:


private class MyPagerAdapter extends PagerAdapter {



int numberOfPages = cards.size();

int[] backgroundcolor = {
0xFF101010};

@Override
public int getCount() {
return numberOfPages;
}

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

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

//select Card on current position from List of cards
final Card tempCard = cards.get(position);

//set TextView with deck title
TextView textView = new TextView(DeckViewActivity.this);
textView.setTextColor(Color.WHITE);
textView.setTextSize(30);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setText(tempCard.getTitle() + " (" + String.valueOf(position + 1) + "/" + cards.size() + ")");


//set ImageView with deckcover
ImageView imageView = new ImageView(DeckViewActivity.this);
ViewGroup.LayoutParams imageParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(imageParams);

int finalHeight = viewPager.getMeasuredHeight();
int finalWidth = viewPager.getMeasuredWidth();

//Load Bitmap from assets
InputStream inputStream = null;

try {
inputStream = getAssets().open(tempCard.getPicture());
imageView.setImageBitmap(decodeSampledBitmapFromResource(inputStream, finalWidth, finalHeight));
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

//imageView.setImageResource(res[position]);


LinearLayout layout = new LinearLayout(DeckViewActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
layout.setBackgroundColor(backgroundcolor[0]);
layout.setLayoutParams(layoutParams);
layout.addView(textView);
layout.addView(imageView);

final int page = position;
layout.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {

}});

container.addView(layout);
return layout;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}

}

No comments:

Post a Comment