基于MVVM实现图片浏览Demo

本文详细介绍了在Android应用中,如何使用ViewModel、LiveData和数据绑定实现一个简单的图片轮播功能,包括ViewModel的初始化、图片切换逻辑以及界面组件的交互设计。
摘要由CSDN通过智能技术生成

在这里插入图片描述

1.MainActivity

public class MainActivity extends AppCompatActivity {

		private ActivityMainBinding binding;

		@Override
		protected void onCreate(Bundle savedInstanceState) {
				super.onCreate(savedInstanceState);
				binding = ActivityMainBinding.inflate(getLayoutInflater());
				setContentView(binding.getRoot());

				ImageViewModel imageViewModel = ViewModelProviders.of(this).get(ImageViewModel.class);
				imageViewModel.init();

				imageViewModel.getCurImage().observe(this, this::onChanged);

				binding.last.setOnClickListener(view -> {
						imageViewModel.lastImage(() -> {
								Toast.makeText(this, "已经是第一张图片!!!", Toast.LENGTH_SHORT).show();
						});
				});

				binding.next.setOnClickListener(view -> {
						imageViewModel.nextImage(() -> {
								Toast.makeText(this, "没有下一张图片!!!", Toast.LENGTH_SHORT).show();
						});
				});

		}

		private void onChanged(Integer drawable) {
				@SuppressLint("UseCompatLoadingForDrawables")
				Drawable newDrawable = getResources().getDrawable(drawable, null);
				binding.image.setImageDrawable(newDrawable);
		}
}

2.ViewModel

public class ImageViewModel extends ViewModel {

		private final MutableLiveData<Integer> curImage = new MutableLiveData<>();

		private final List<Integer> images = ImageRepository.getInstance().getImages();

		public MutableLiveData<Integer> getCurImage() {
				return curImage;
		}

		public void init() {
				if (images.size() > 0) {
						curImage.postValue(images.get(0));
				}
		}

		public void lastImage(Runnable runnable) {
				int index = images.indexOf(curImage.getValue());
				if (index > 0) {
						curImage.postValue(images.get(index - 1));
				} else {
						runnable.run();
				}
		}

		public void nextImage(Runnable runnable) {
				int index = images.indexOf(curImage.getValue());
				if (index < images.size() - 1) {
						curImage.postValue(images.get(index + 1));
				} else {
						runnable.run();
				}
		}
}

3.Repository

public class ImageRepository {

    private static ImageRepository IMAGE_REPOSITORY = null;

    private List<Integer> images = new ArrayList<>();

    private ImageRepository() {
        images.add(R.drawable.ic_0);
        images.add(R.drawable.ic_1);
        images.add(R.drawable.ic_2);
    }

    public static ImageRepository getInstance() {
        if (IMAGE_REPOSITORY == null) {
            synchronized (ImageRepository.class) {
                IMAGE_REPOSITORY = new ImageRepository();
            }
        }
        return IMAGE_REPOSITORY;
    }

    public List<Integer> getImages() {
        return images;
    }
}

4.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:contentDescription="TODO" />


    <Button
        android:id="@+id/last"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:text="上一个"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintRight_toLeftOf="@+id/next"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/image" />


    <Button
        android:id="@+id/next"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="50dp"
        android:text="下一个"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_weight="1"
        app:layout_constraintLeft_toRightOf="@+id/last"
        app:layout_constraintTop_toBottomOf="@+id/image" />


</androidx.constraintlayout.widget.ConstraintLayout>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值