根据当前滚动位置在Recyclerview中自动滚动

时间:2016-08-16 08:54:09

标签: android android-recyclerview recycler-adapter

我正在开发一个演示聊天应用程序,如果我发送消息,那么我会在2秒后收到一条默认消息作为回复。 recyclerview将自动滚动到最后位置。一切正常。

但我有一个要求,如果我滚动到顶部/中间或除了结尾之外的任何地方,如果我收到来自另一方的任何消息,我不想自动滚动到结束。简化工作应该与Whatsup相同。请找我的活动课。

 public class ChatRoomActivity extends AppCompatActivity {

    private String TAG = ChatRoomActivity.class.getSimpleName();

    private RecyclerView recyclerView;
    private ChatRoomThreadAdapter mAdapter;
    private ArrayList<Message> messageArrayList;
    private EditText inputMessage;
    private ImageView btnSend;
    String selfUserId ="100";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_driver_chat);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        inputMessage = (EditText) findViewById(R.id.etChatMessage);
        btnSend = (ImageView) findViewById(R.id.btnYou);


        getSupportActionBar().setTitle(getResources().getString(R.string.driver_prof_name));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);



        recyclerView = (RecyclerView) findViewById(R.id.rvChatList);

        messageArrayList = new ArrayList<>();

        // self user id is to identify the message owner

        mAdapter = new ChatRoomThreadAdapter(this, messageArrayList, selfUserId);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
                new CountDownTimer(2000, 1000) {
                    public void onFinish() {
                        // When timer is finished
                        // Execute your code here
                        fetchChatThread();

                    }

                    public void onTick(long millisUntilFinished) {
                        // millisUntilFinished    The amount of time until finished.
                    }
                }.start();
            }
        });

    }



    /**
     * Handling new push message, will add the message to
     * recycler view and scroll it to bottom
     * */


    /**
     * Posting a new message in chat room
     * will make an http call to our server. Our server again sends the message
     * to all the devices as push notification
     * */
    private void sendMessage() {
        final String strmessage = this.inputMessage.getText().toString().trim();

        if (TextUtils.isEmpty(strmessage)) {
            Toast.makeText(getApplicationContext(), "Enter a message", Toast.LENGTH_SHORT).show();
            return;
        }


        this.inputMessage.setText("");
        String commentId = "message_id";
        String commentText = strmessage;
        Calendar c = Calendar.getInstance();
        SimpleDateFormat dateformat = new SimpleDateFormat("hh:mm aa");
        String datetime = dateformat.format(c.getTime());
        String createdAt = datetime;

        String userId = selfUserId;
        String userName = "name";
        User user = new User(userId, userName, null);

        Message message = new Message();
        message.setId(commentId);
        message.setMessage(commentText);
        message.setCreatedAt(createdAt);
        message.setUser(user);

        messageArrayList.add(message);

        mAdapter.notifyDataSetChanged();
        if (mAdapter.getItemCount() > 1) {
            // scrolling to bottom of the recycler view
            recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
        }
    }


    /**
     * Fetching all the messages of a single chat room
     * */
    private void fetchChatThread() {

        String commentId = "message_id";
        String commentText = "Replay from Other";
        Calendar c = Calendar.getInstance();
        SimpleDateFormat dateformat = new SimpleDateFormat("hh:mm aa");
        String datetime = dateformat.format(c.getTime());
        String createdAt = datetime;

        String userId = "user_id";
        String userName = "username";
        User user = new User(userId, userName, null);

        Message message = new Message();
        message.setId(commentId);
        message.setMessage(commentText);
        message.setCreatedAt(createdAt);
        message.setUser(user);

        messageArrayList.add(message);
        mAdapter.notifyDataSetChanged();
        if (mAdapter.getItemCount() > 1)
        {
            recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, null, mAdapter.getItemCount() - 1);
        }

            }

适配器类是

public class ChatRoomThreadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static String TAG = ChatRoomThreadAdapter.class.getSimpleName();

    private String userId;
    private int SELF = 100;
    private static String today;

    private Context mContext;
    private ArrayList<Message> messageArrayList;

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView message, timestamp;

        public ViewHolder(View view) {
            super(view);
            message = (TextView) itemView.findViewById(R.id.tvChatMessage);
            timestamp = (TextView) itemView.findViewById(R.id.tvChatTimeStamp);
        }
    }


    public ChatRoomThreadAdapter(Context mContext, ArrayList<Message> messageArrayList, String userId) {
        this.mContext = mContext;
        this.messageArrayList = messageArrayList;
        this.userId = userId;

        Calendar calendar = Calendar.getInstance();
        today = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView;

        // view type is to identify where to render the chat message
        // left or right
        if (viewType == SELF) {
            // self message
            itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_driver_chat_itself, parent, false);
        } else {
            // others message
            itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.custom_driver_chat_others, parent, false);
        }


        return new ViewHolder(itemView);
    }


    @Override
    public int getItemViewType(int position) {
        Message message = messageArrayList.get(position);
        if (message.getUser().getId().equals("100")) {
            return SELF;
        }

        return position;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        Message message = messageArrayList.get(position);
        ((ViewHolder) holder).message.setText(message.getMessage());

//        String timestamp = getTimeStamp(message.getCreatedAt());
//
//        if (message.getUser().getName() != null)
//            timestamp = message.getUser().getName() + ", " + timestamp;

        ((ViewHolder) holder).timestamp.setText(message.getCreatedAt());
    }

    @Override
    public int getItemCount() {
        return messageArrayList.size();
    }

    public static String getTimeStamp(String dateStr) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = "";

        today = today.length() < 2 ? "0" + today : today;

        try {
            Date date = format.parse(dateStr);
            SimpleDateFormat todayFormat = new SimpleDateFormat("dd");
            String dateToday = todayFormat.format(date);
            format = dateToday.equals(today) ? new SimpleDateFormat("hh:mm a") : new SimpleDateFormat("dd LLL, hh:mm a");
            String date1 = format.format(date);
            timestamp = date1.toString();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return timestamp;
    }

0 个答案:

没有答案