gpt4 book ai didi

java - 简单 ViewPager - 单一布局

转载 作者:行者123 更新时间:2023-11-30 03:32:36 25 4
gpt4 key购买 nike

我正在尝试从一组图像中创建一个简单的 ViewPager。

我的数组是:

<string-array name="ot_images">
<item>"file:///android_res/drawable/ot_100.jpg"</item>
<item>"file:///android_res/drawable/ot_101.jpg"</item>
<item>"file:///android_res/drawable/ot_102.jpg"</item>
<item>"file:///android_res/drawable/ot_103.jpg"</item>

我的布局是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
android:id="@+id/iView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />

</RelativeLayout>

到目前为止 MyPagerAdapter.java

public class MyPagerAdapter extends PagerAdapter{

public int getCount() {
return 5;
}

public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int resId = 0;
switch (position) {
case 0:
resId = R.layout.farleft;
break;
case 1:
resId = R.layout.left;
break;
case 2:
resId = R.layout.middle;
break;
case 3:
resId = R.layout.right;
break;
case 4:
resId = R.layout.farright;
break;
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
@Override
public Parcelable saveState() {
return null;
}
}

我已遵循本教程: Android User Interface Design: Horizontal View Paging

一切正常,但我的问题是:

如何使用 1 种布局而不是 5 种布局来使用本教程?谢谢!

最佳答案

您只需定义一个通用布局,比如 common_layout.xml 并通过覆盖 instantiateItem 方法将其放置在 viewpager 的容器中。在下面的示例中,我假设您有一个带有 id 文本的 TextView。

public Object instantiateItem(View collection, int position) {

LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.common_layout, null);
switch (position) {
case 0:
((TextView)view.findViewById(R.id.text)).setText("One");
break;
case 1:
((TextView)view.findViewById(R.id.text)).setText("Two");
break;
case 2:
((TextView)view.findViewById(R.id.text)).setText("Three");
break;
case 3:
((TextView)view.findViewById(R.id.text)).setText("Four");
break;
case 4:
((TextView)view.findViewById(R.id.text)).setText("Five");
break
}

((ViewPager) collection).addView(view, 0);
return view;
}

关于java - 简单 ViewPager - 单一布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17190537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com