使用android studio实现三张图片轮播
时间: 2023-05-24 14:07:34 浏览: 346
Android实现图片轮播列表
以下是使用android studio实现三张图片轮播的步骤:
1. 在xml布局文件中添加ViewPager控件和指示器控件,如下所示:
```
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="8dp"
android:clipToPadding="false"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:overScrollMode="never"/>
<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@android:color/transparent"
app:tabIndicatorColor="@color/colorAccent"
app:tabIndicatorHeight="4dp"
app:tabSelectedTextColor="@color/colorBlack"
app:tabTextColor="@color/colorGray"/>
```
2. 创建一个自定义PagerAdapter类,继承自FragmentPagerAdapter,这里假设图片已经存在于drawable中,代码如下:
```
public class MyPagerAdapter extends FragmentPagerAdapter {
private final List<Integer> imageList = Arrays.asList(R.drawable.image1, R.drawable.image2, R.drawable.image3); //图片资源列表
public MyPagerAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
@NonNull
@Override
public Fragment getItem(int position) {
return MyFragment.newInstance(imageList.get(position));
}
@Override
public int getCount() {
return imageList.size();
}
}
```
3. 创建一个自定义Fragment类,用于显示每个图片,代码如下:
```
public class MyFragment extends Fragment {
private int imageId; //图片资源id
public MyFragment() {
}
public static MyFragment newInstance(int imageId) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("imageId", imageId);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
imageId = getArguments().getInt("imageId");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my, container, false);
ImageView imageView = view.findViewById(R.id.imageView);
imageView.setImageResource(imageId);
return view;
}
}
```
4. 在Activity中初始化ViewPager和指示器,代码如下:
```
MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
ViewPager viewPager = findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager, true);
```
5. 运行程序,即可看到图片轮播效果。
以上就是使用android studio实现三张图片轮播的步骤。
阅读全文