1
我嘗試將圖像及其文本和tts一起滑動。我用過ViewPageAdapter。 代碼是使用視圖適配器類滑動圖像
public class ViewPagerAdapter extends PagerAdapter{
Activity activity;
int imageArray[];
String[] arrToDisplay;
public ViewPagerAdapter(Activity act, int[] imgArra, String[] arrayObject) {
imageArray = imgArra;
activity = act;
arrToDisplay = arrayObject;
}
public int getCount() {
return imageArray.length;
}
public Object instantiateItem(View collection, int position) {
ImageView view = new ImageView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setScaleType(ScaleType.FIT_XY);
view.setBackgroundResource(imageArray[position]);
((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;
}
}
XML:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:orientation="vertical" >
<!--ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/a_elephant" /-->
<android.support.v4.view.ViewPager
android:id="@+id/myfivepanelpager"
android:layout_width="match_parent"
android:layout_height="494dp" />
</LinearLayout>
Main.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, arrAnimals1, arrAnimals);
ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(0);
}
正確
上面的代碼滑動圖像。問題是我想顯示文本以及tts。我試過這段代碼來顯示適配器類中的文本,但它不起作用:
public Object instantiateItem(View collection, int position) {
LayoutInflater inflater = (LayoutInflater)collection.getContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.animals, null);
ImageView im=(ImageView) layout.findViewById(R.id.imageView1);
im.setBackgroundResource(imageArray[position]);
TextView dsc=(TextView) layout.findViewById(R.id.txtObjName);
dsc.setText("asdfasdf");
((ViewPager) collection).addView(layout, 0);
return layout;
}
請幫忙。
感謝, ITIN
安置自己的'animals.xml'文件的XML。還有一點,如果你想'setScaleType',你應該使用'setImageResource',不要使用'setImageBackgroundResource'。 – Wenhui
上面的xml代碼是來自animal.xml – itin
我看到xml文件有ViewPager,並且沒有ImageView。我錯過了什麼嗎? – Wenhui