gpt4 book ai didi

android - 从 View 模型类中获取 Activity 的上下文

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:45:27 25 4
gpt4 key购买 nike

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

这是帖子的适配器

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 方法来自 View 模型类:

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)

但它按时显示错误。

最佳答案

尝试使用 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);
}
}

关于android - 从 View 模型类中获取 Activity 的上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52032384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com