我正在创建一个列表视图,人们可以在阅读时查看列表视图中的书籍。当他们选择一本书时,该行的alpha值会变为0.2f,并且会出现一个吐司,告诉他们他们会读这本书。我试图这样做,以便当一本书被选中时,他们也可以通过再次点击它来取消选择,这将使alpha回到1f。
我在onItemClick方法中创建了一个if else循环,它允许我取消选择点击的行,但它遵循的模式是第一次点击变为0.2f,第二次变为1f,第三次变为0.2f等等。相反,我希望只有0.2f的行能够转到1f,反之亦然。
这是我的代码:
typedef struct VisibleType VisibleType;
}
答案 0 :(得分:1)
在考虑您的代码的情况下解决其他两个答案,为书行创建BookAdapter,BookModel和xml:
书行的xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="72dp">
<TextView
android:id="@+id/title"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
BookModel:
public class BookModel {
public String name;
public boolean isRead;
}
BookAdapter:
public class BookAdapter extends BaseAdapter {
private Context context;
private List<BookModel> books;
static class Holder{
TextView mTvName;
}
public BookAdapter(Context context, List<BookModel> books){
this.context = context;
this.books = books;
}
@Override
public int getCount() {
return books.size();
}
@Override
public Object getItem(int position) {
return books.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder;
if(convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.book_row, parent, false);
holder = new Holder();
holder.mTvName = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
}else{
holder = (Holder) convertView.getTag();
}
final BookModel bookModel = books.get(position);
if(bookModel != null){
holder.mTvName.setText(bookModel.name);
if(bookModel.isRead){
holder.mTvName.animate().alpha(0.2f);
bookModel.isRead = true;
}else{
holder.mTvName.animate().alpha(1f);
bookModel.isRead = false;
}
}
return convertView;
}
}
图书活动布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.divshark.booksample.Books">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
<ListView
android:id="@+id/booksListView"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:layout_below="@+id/toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
然后实施您的活动编辑 - 现在图书阅读会保留在偏好设置中:
public class Books extends AppCompatActivity {
public List<BookModel> books;
private SharedPreferences mSharedPreferences;
private static final String SHARED_PREFERENCES = "SharedPrefs";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_books);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSharedPreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
ListView booksListView = (ListView)findViewById(R.id.booksListView);
books = createBooks();
final BookAdapter adapter = new BookAdapter(this, books);
booksListView.setAdapter(adapter);
final MediaPlayer mPlayer = MediaPlayer.create(this, R.raw.pindrop);
booksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final BookModel bookModel = books.get(position);
if (!bookModel.isRead) {
Toast.makeText(getApplicationContext(), "You Read " + bookModel.name, Toast.LENGTH_LONG).show();
view.animate().alpha(0.2f);
mPlayer.start();
bookModel.isRead = true;
if(mSharedPreferences != null){
mSharedPreferences.edit().putBoolean(bookModel.name, bookModel.isRead).apply();
}
adapter.notifyDataSetChanged();
} else {
view.animate().alpha(1f);
mPlayer.start();
bookModel.isRead = false;
if(mSharedPreferences != null){
mSharedPreferences.edit().putBoolean(bookModel.name, bookModel.isRead).apply();
}
adapter.notifyDataSetChanged();
}
}
});
}
/**
* Creates an ArrayList<BookModel>
* @return - List<BookModel>
*/
public List<BookModel> createBooks(){
final ArrayList<String> topBooks = new ArrayList<String>(Arrays.asList("1984", "To Kill a Mockingbird", "Pride and Prejudice",
"Harry Potter and the Sorcerer's Stone", "The Great Gatsby", "Jane Eyre", "Wuthering Heights", "The Catcher in the Rye",
"The Hobbit", "Brave New World", "The Lord of the Rings: The Fellowship of the Ring", "Don Quixote",
"Catch-22", "The Count of Monte Cristo", "Harry Potter and the Goblet of Fire", "The Grapes of Wrath", "The Adventures of Huckleberry Finn",
"The Diary of a Young Girl", "Gone with the Wind", "Harry Potter and the Deathly Hallows", "Moby Dick", "Harry Potter and the Half-Blood Prince", "War and Peace",
"Animal Farm", "Anna Karenina", "Ulysses", "Lord of the Flies", "The Divine Comedy", "One Hundred Years of Solitude", "Frankenstein", "The Perks of Being a Wallflower",
"The Fault in Our Stars", "Good to Great", "Harry Potter and the Chamber of Secrets", "Harry Potter and the Order of the Phoenix", "Harry Potter and the Prisoner of Azkaban",
"The Amazing Adventures of Kavalier & Clay", "The Hunger Games", "The Lord of the Rings: The Two Towers", "The Lord of the Rings: The Return of the King", "The Maze Runner",
"Looking for Alaska", "Fahrenheit 451", "Hamlet", "Gullivers Travels", "The Canterbury Tales", "Rebecca", "The Brothers Karamazov", "Lover Awakened", "At Grave's End"));
List<BookModel> books = new ArrayList<>(topBooks.size());
for(int i = 0; i < topBooks.size(); i++){
BookModel bookModel = new BookModel();
bookModel.name = topBooks.get(i);
if(mSharedPreferences != null) {
// sets the IsRead field from value in preferences
bookModel.isRead = mSharedPreferences.getBoolean(bookModel.name, false);
}else {
bookModel.isRead = false;
// Open preferences to write the value in on load
mSharedPreferences = getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
// Stores the book in shared preferences as un-read
mSharedPreferences.edit().putBoolean(bookModel.name, false).apply();
}
books.add(bookModel);
}
return books;
}
}
和样式以防万一你需要它们:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
祝你好运,快乐的编码!
答案 1 :(得分:0)
您需要实现自定义适配器以及切换选择功能以实现预期的行为。这是一个例子。
public class ToggleSelectionListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Cursor mCursor;
private SparseBooleanArray selectedItems;
public ToggleSelectionListAdapter(Cursor cursor) {
mCursor = cursor;
selectedItems = new SparseBooleanArray();
}
public void toggleSelection(int pos) {
if (selectedItems.get(pos, false)) {
selectedItems.delete(pos);
} else {
selectedItems.put(pos, true);
}
notifyItemChanged(pos);
}
public int getSelectedItemCount() {
return selectedItems.size();
}
public void clearSelections() {
selectedItems.clear();
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(final View itemView) {
super(itemView);
// Initialize your items of each row here
}
public void bindView(int pos) {
try {
if (mCursor.isClosed())
return;
mCursor.moveToPosition(pos);
// Maintain a checked item list so that you can have a track if the item is clicked or not
if (checkedItems.contains(number) itemView.setBackgroundResource(R.drawable.background_selected);
else itemView.setBackgroundResource(R.drawable.background_normal);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkedItems.contains(number)) {
checkedItems.remove(number);
} else {
checkedItems.add(number);
}
// Get the index of which item should toggle the background
int idx = mRecyclerView.getChildAdapterPosition(v);
toggleSelection(idx);
}
}
});
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
ViewHolder vh = (ViewHolder) holder;
vh.bindView(position);
}
}
@Override
public int getItemCount() {
if (mCursor == null) {
return 0;
}
int n = mCursor.getCount();
return n;
}
@Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
synchronized public void swapCursor(Cursor cursor) {
mCursor = cursor;
notifyDataSetChanged();
}
}