我的代码基于我发现的使用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)
但是它会按时显示错误。
答案 0 :(得分:3)
尝试:android:onClick="@{(view) -> viewModel.onClickPost(view)}"
还更改onClickPost
以进入视图。然后,您可以在视图上使用view.getContext()
方法来访问存储在该视图中的Context。
但是,由于ViewModels不应引用包含Activity上下文的视图或任何其他类,因此将用于启动Activity的逻辑放在ViewModel中是非常不合适的。您绝对应该考虑另外一个地方。
就我的代码而言,个人而言,如果它是一个简单的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>
在此处查看侦听器绑定:https://developer.android.com/topic/libraries/data-binding/expressions#listener_bindings
但是,根据所需的数据量,您可能希望将startActivity代码放在最适合应用程序设计的其他类中。
答案 1 :(得分: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 :(得分:2)
尝试使用SingleLiveEvent
这是Googles architecture samples 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);
}
}