【发布时间】:2016-08-24 06:07:04
【问题描述】:
我想做类似this 的事情,我使用了cardview 和recyclerview。我在下面添加了最喜欢的按钮卡片视图,您可以看到完整的代码。在 recyclerview 适配器中,我根据位置打印 Toast 并且它工作正常,现在我需要将位置的 int 值保存在 arraylist 中的共享首选项中,并在下一个意图中显示这些 arraylist。
这是我的 recyclerview 适配器
public void onBindViewHolder(NameViewHolder holder, final int position) {
holder.textView.setText(names.get(position).textView);
holder.favourite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(view.getContext());
SharedPreferences.Editor editor = sp.edit();
editor.putInt("key", position); //may be or may not be.
//add code here to save position in array
Toast.makeText(view.getContext(),"Fav "+position,Toast.LENGTH_SHORT).show();
}
});
cardview.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:orientation="vertical"
app:cardBackgroundColor="@android:color/transparent"
app:cardCornerRadius="8dp"
app:cardElevation="3dp"
app:cardPreventCornerOverlap="false"
app:cardUseCompatPadding="true">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:paddingTop="3dp"
android:textAlignment="center"
android:textColor="#ff9901"
android:textSize="35sp"
android:textStyle="italic" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:id="@+id/favourite"
android:src="@drawable/star"
android:background="@android:color/transparent"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
提供我从首选项中获取数组列表以及如何在 ListView 中使用。
【问题讨论】:
-
你能添加你的活动java代码吗?
-
我需要发布哪部分代码?我已经发布了我如何调用收藏按钮。如果在列表中按下收藏按钮,则应将项目添加到 sharedprefrences 中。
标签: android sharedpreferences android-adapter android-recyclerview android-sharedpreferences