我正在编写一个四重奏游戏,因此我需要一个包含每张卡片所有属性的画廊。我找到了一个带有自定义PagerAdapter的ViewPager示例:http://android-er.blogspot.de/2014/04/example-of-viewpager-with-custom.html
对于简单的图库视图,这非常好,但我想包含一个 XML 文件(例如我的游戏活动),而不是显式定义所有布局参数。感谢您的任何想法!
这是我的适配器类:
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);
}
}
您的instantiateItem()
方法可以使用LayoutInflater
(通过getLayoutInflater()
从您的活动中获取)来膨胀布局,而不是在 Java 中设置小部件。
或者,如果将布局包装在片段中,则可以使用 FragmentPagerAdapter
。