一旦在recyclerview适配器上更新数据,如何将TypeFace从BOLD更改为NORMAL?

时间:2018-02-16 03:31:54

标签: android firebase firebase-realtime-database android-recyclerview android-adapter

我正在使用Firebase数据和RecyclerView Adapter

该方案是当用户点击列表时,初始状态UNREAD将更改为READ,因此TypeFace应从BOLD更改为{{1} }}。

我目前将状态从NORMAL更改为UNREAD的后端流程正在运行并更新到Firebase,但我的特定READ项的界面不会更改{{ 1}}到RecyclerView

我认为无需回忆 Firebase数据 以便读取状态,但界面应根据用户点击进行更改。

任何人都可以帮助我吗?

BOLD

NORMAL

NotificationActivity.java

package com.myapp.activity.notification;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.material.nereeducation.R;
import com.material.nereeducation.adapter.AdapterNotification;
import com.material.nereeducation.model.Notification;
import com.material.nereeducation.utils.Tools;
import com.material.nereeducation.widget.LineItemDecoration;

import java.util.ArrayList;
import java.util.List;

public class NotificationActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private AdapterNotification mAdapter;
    private ActionModeCallback actionModeCallback;
    private ActionMode actionMode;
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        initToolbar();
        initComponent();
        Tools.setSystemBarColor(this, R.color.black);
    }

    private void initToolbar() {
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Notifications");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    private List<Notification> items = new ArrayList<>();
    private LinearLayout messageEmptyList;
    private void initComponent() {

        messageEmptyList = findViewById(R.id.messageEmptyList);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new LineItemDecoration(this, LinearLayout.VERTICAL));
        recyclerView.setHasFixedSize(true);

        //set data and list adapter
        mAdapter = new AdapterNotification(this, items);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnClickListener(new AdapterNotification.OnClickListener() {

            @Override
            public void onItemClick(View view, Notification obj, int pos) {
                if (mAdapter.getSelectedItemCount() > 0) {
                    enableActionMode(pos);
                } else {
                    // read the inbox which removes bold from the row
                    Notification notification = mAdapter.getItem(pos);
                    Toast.makeText(getApplicationContext(), "Read: " + notification.sender_id, Toast.LENGTH_SHORT).show();

                    updateStatus(notification.notificationId,"read",pos);

                }
            }

            @Override
            public void onItemLongClick(View view, Notification obj, int pos) {
                enableActionMode(pos);
            }
        });

        actionModeCallback = new ActionModeCallback();

        getNotificationData();

    }

    private void getNotificationData()
    {
        items.clear();
        GsonBuilder builder = new GsonBuilder();
        final Gson gson = builder.create();

        FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
        String uuid = firebaseAuth.getUid();

        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference databaseReference = firebaseDatabase.getReference();

        databaseReference.child("notifications/"+uuid+"/data_notification").orderByChild("status").startAt("read").endAt("unread").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if(dataSnapshot.getValue() != null)
                {
                    for(DataSnapshot snapshot: dataSnapshot.getChildren())
                    {
                        String dataReceived = gson.toJson(snapshot.getValue());
                        Notification notificationItems = gson.fromJson(dataReceived, Notification.class);
                        items.add(notificationItems);
                    }
                    mAdapter.notifyDataSetChanged();
                }else
                {
                    messageEmptyList.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void updateStatus(final String notificationId, String status, final int position) {
        FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
        String uuid = firebaseAuth.getUid();

        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference databaseReference = firebaseDatabase.getReference();

        databaseReference.child("notifications/"+uuid+"/data_notification").child(notificationId).child("status").setValue(status
        ).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                mAdapter.notifyItemChanged(position); //Problem here - how to update text from BOLD to NORMAL for this item?
            }
        });
    }

    private void enableActionMode(int position) {
        if (actionMode == null) {
            actionMode = startSupportActionMode(actionModeCallback);
        }
        toggleSelection(position);
    }

    private void toggleSelection(int position) {
        mAdapter.toggleSelection(position);
        int count = mAdapter.getSelectedItemCount();

        if (count == 0) {
            actionMode.finish();
        } else {
            actionMode.setTitle(String.valueOf(count));
            actionMode.invalidate();
        }
    }

    private class ActionModeCallback implements ActionMode.Callback {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.getMenuInflater().inflate(R.menu.menu_delete, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            int id = item.getItemId();
            if (id == R.id.action_delete) {
                deleteInboxes();
                mode.finish();
                return true;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mAdapter.clearSelections();
            actionMode = null;
        }
    }

    private void deleteInboxes() {
        List<Integer> selectedItemPositions = mAdapter.getSelectedItems();
        for (int i = selectedItemPositions.size() - 1; i >= 0; i--) {
            mAdapter.removeData(selectedItemPositions.get(i));
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        } else {
            Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);
    }
}

4 个答案:

答案 0 :(得分:0)

你也需要为这种情况处理ELSE

if(notification.status.equals("unread")){
   holder.from.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
   holder.title.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
}else{
   holder.from.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
   holder.title.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
}

答案 1 :(得分:0)

如果你想在适配器中设置textview不同的字体或颜色,你需要检查每个位置,所以在你的情况下,你只需要为textview设置字体粗体,你必须为默认的textview字体再次设置字体。

在适配器中设置字体Normal。

为textview设置文本默认字体Normal,如下所示。

holder.from.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
   holder.title.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));

然后检查未读的项目状态

   if(notification.status.equals("unread")){
       holder.from.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
       holder.title.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
    }

答案 2 :(得分:0)

所以我猜你的问题是状态(读/未读)应用于数据库,但没有反映在回收站视图上。

如果这是问题,主要是因为你没有处理列表的数据更改方法(并使用新值更新它)。

您目前正在使用它来获取数据:

back.setOnClickListener(new View.OnClickListener() {
    if(TextUtils.isEmpty(et1.getText().toString()) {
        //your first edit text is empty
    }
});

这也无法帮助您控制更改的项目。

可能的解决方案

解决问题的方法是使用(FirebaseUI)数据库而不是自定义适配器。

FirebaseUI将侦听更改并更新列表。

编辑2

使用ChildEventListener而不是Listener For Single Value事件

而不是:

       databaseReference.child("notifications/"+uuid+"/data_notification").orderByChild("status").startAt("read").endAt("unread").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {.....

使用它:

     databaseReference.child("notifications/"+uuid+"/data_notification").orderByChild("status").startAt("read").endAt("unread").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {.....

答案 3 :(得分:0)

我相信您应该这样设置字体:

if ("unread".equals(notification.status)) {
    holder.from.setTypeface(null, Typeface.BOLD);
    holder.title.setTypeface(null, Typeface.BOLD);
} else {
    holder.from.setTypeface(null, Typeface.NORMAL);
    holder.title.setTypeface(null, Typeface.NORMAL);
}

RecyclerView正在重用该视图,因此一旦将字体设置为粗体,则需要在下次使用它时将其设置为正常。