要实现类似于Android画廊效果,可以使用RecyclerView和ViewPager组合来实现。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.ViewHolder> {
private List<Drawable> images;
public GalleryAdapter(List<Drawable> images) {
this.images = images;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gallery, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.image.setImageDrawable(images.get(position));
}
@Override
public int getItemCount() {
return images.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
public ViewHolder(@NonNull View itemView) {
super(itemView);
image = itemView.findViewById(R.id.imageView);
}
}
}
public class ViewPagerAdapter extends PagerAdapter {
private List<Drawable> images;
public ViewPagerAdapter(List<Drawable> images) {
this.images = images;
}
@Override
public int getCount() {
return images.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView imageView = new ImageView(container.getContext());
imageView.setImageDrawable(images.get(position));
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
viewPager = findViewById(R.id.viewPager);
List<Drawable> images = new ArrayList<>();
images.add(getDrawable(R.drawable.image1));
images.add(getDrawable(R.drawable.image2));
images.add(getDrawable(R.drawable.image3));
GalleryAdapter galleryAdapter = new GalleryAdapter(images);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
recyclerView.setAdapter(galleryAdapter);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(images);
viewPager.setAdapter(viewPagerAdapter);
}
}
通过以上步骤,即可实现类似于Android画廊效果的功能。RecyclerView用于显示缩略图列表,ViewPager用于显示大图。可以根据需求自定义布局和样式来实现更丰富的效果。