我想在我的Android屏幕的上半部分放一个旋转木马。
我喜欢Bootstrap旋转木马:
http://www.w3schools.com/bootstrap/bootstrap_carousel.asp
我不确定最好的方法来解决这个问题?我在屏幕的上半部分使用GridView吗?
答案 0 :(得分:9)
首先,您必须在xml中创建一个Viewpager
,如:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:id="@+id/relativeLayout">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
对于自定义Adapter
,您需要创建一个res / layout / pager_item.xml,用于对Adapter
中的视图进行通知并生成视图:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView" />
</LinearLayout>
之后,您可以创建自定义Adapter
来设置ViewPager
:
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
private LayoutInflater mLayoutInflater;
private int[] mResources;
public CustomPagerAdapter(Context context, int[] resources) {
mContext = context;
mResources = resources;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return mResources.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
container.addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
然后将以下代码放入onCreate
中的Activity
:
mViewPager = (ViewPager) findViewById(R.id.pager);
// This is just an example. You can use whatever collection of images.
int[] mResources = {
R.drawable.first,
R.drawable.second,
R.drawable.third,
R.drawable.fourth,
R.drawable.fifth,
R.drawable.sixth
};
CustomPagerAdapter mCustomPagerAdapter = new CustomPagerAdapter(this, mResources);
mViewPager.setAdapter(mCustomPagerAdapter);
查看以下教程以获取更多详细信息:http://codetheory.in/android-image-slideshow-using-viewpager-pageradapter/
答案 1 :(得分:4)
简单地使用Android Image Slider,它是一个美观且易于使用的库: https://github.com/daimajia/AndroidImageSlider