从视图模型类获取活动的上下文

问题描述 投票:5回答:3

我的代码基于我发现的使用Android架构组件和数据绑定的示例。这对我来说是一种新的方式,它的编码方式使得很难使用所点击的帖子的信息正确地打开新活动。

这是帖子的适配器

class PostListAdapter : RecyclerView.Adapter<PostListAdapter.ViewHolder>() {
    private lateinit var posts: List<Post>

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostListAdapter.ViewHolder {
        val binding: ItemPostBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.item_post,
            parent, false
        )

        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: PostListAdapter.ViewHolder, position: Int) {
        holder.bind(posts[position])
    }

    override fun getItemCount(): Int {
        return if (::posts.isInitialized) posts.size else 0
    }

    fun updatePostList(posts: List<Post>) {
        this.posts = posts
        notifyDataSetChanged()
    }

    inner class ViewHolder(private val binding: ItemPostBinding) : RecyclerView.ViewHolder(binding.root) {
        private val viewModel = PostViewModel()

        fun bind(post: Post) {
            viewModel.bind(post)
            binding.viewModel = viewModel
        }
    }
}

bind方法来自视图模型类:

class PostViewModel : BaseViewModel() {
    private val image = MutableLiveData<String>()
    private val title = MutableLiveData<String>()
    private val body = MutableLiveData<String>()

    fun bind(post: Post) {
        image.value = post.image
        title.value = post.title
        body.value = post.body
    }

    fun getImage(): MutableLiveData<String> {
        return image
    }

    fun getTitle(): MutableLiveData<String> {
        return title
    }

    fun getBody(): MutableLiveData<String> {
        return body
    }

    fun onClickPost() {
        // Initialize new activity from here, perhaps?
    }
}

在布局XML中,设置onClick属性

android:onClick =“@ {() - > viewModel.onClickPost()}”

指向这个onClickPost方法确实有效,但我不能从那里初始化Intent。我尝试了许多方法来获取MainActivitiy的背景,但没有成功,例如

val intent = Intent(MainActivity :: getApplicationContext,PostDetailActivity :: class.java)

但它会按时显示错误。

android mvvm android-recyclerview android-databinding android-viewmodel
3个回答
3
投票

尝试:android:onClick="@{(view) -> viewModel.onClickPost(view)}"

同时更改onClickPost以获取视图。然后,您可以在视图上使用view.getContext()方法来访问存储在该视图中的Context。

但是,由于ViewModel不应引用包含Activity上下文的视图或任何其他类,因此在ViewModel中放置用于启动Activity的逻辑是不合适的。你一定要考虑一个单独的地方。

就个人而言,对于我的代码,如果它是一个简单的startActivity而没有任何额外的包袱,我创建了一个包含静态方法的独立类。通过数据绑定,我将导入该类并在onClick中使用它来使用我上面提到的方法启动一个新的Activity。

一个例子:

public class ActivityHandler{        
    public static void showNextActivity(View view, ViewModel viewModel){
        Intent intent = new Intent(); //Create your intent and add extras if needed
        view.getContext().startActivity(intent);
    }
}

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <import type="whatever.you.want.ActivityHandler" />
        <variable name="viewmodel" type="whatever.you.want.here.too.ViewModel" />
    </data>

    <Button
        //Regular layout properties
        android:onClick="@{(view) -> ActivityHandler.showNextActivity(view, viewmodel)}"
        />
</layout>

看看Listener Bindings:https://developer.android.com/topic/libraries/data-binding/expressions#listener_bindings

但是,根据所需的数据量,您可能希望将startActivity代码放在最适合您应用程序设计的其他类中。


3
投票

您甚至可以将活动实例传递给模型或布局,但我不喜欢这样。

首选方法是将接口传递给行布局。

在布局数据中声明变量

<variable
    name="onClickListener"
    type="android.view.View.OnClickListener"/>

单击时调用此项

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="@{onClickListener::onClick}"
    >

还从适配器设置此侦听器

 binding.viewModel = viewModel
 binding.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            context.startActivity(new Intent(context, MainActivity.class));
        }
    });

2
投票

尝试使用SingleLiveEvent

以下是来自Googles architecture samples repo的代码(如果它从repo中删除):

import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * A lifecycle-aware observable that sends only new updates after subscription, used for events like
 * navigation and Snackbar messages.
 * <p>
 * This avoids a common problem with events: on configuration change (like rotation) an update
 * can be emitted if the observer is active. This LiveData only calls the observable if there's an
 * explicit call to setValue() or call().
 * <p>
 * Note that only one observer is going to be notified of changes.
 */
public class SingleLiveEvent<T> extends MutableLiveData<T> {

    private static final String TAG = "SingleLiveEvent";

    private final AtomicBoolean mPending = new AtomicBoolean(false);

    @MainThread
    public void observe(LifecycleOwner owner, final Observer<T> observer) {

        if (hasActiveObservers()) {
            Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
        }

        // Observe the internal MutableLiveData
        super.observe(owner, new Observer<T>() {
            @Override
            public void onChanged(@Nullable T t) {
                if (mPending.compareAndSet(true, false)) {
                    observer.onChanged(t);
                }
            }
        });
    }

    @MainThread
    public void setValue(@Nullable T t) {
        mPending.set(true);
        super.setValue(t);
    }

    /**
     * Used for cases where T is Void, to make calls cleaner.
     */
    @MainThread
    public void call() {
        setValue(null);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.