Recyclerview在更新

时间:2016-09-12 05:01:00

标签: java android xml android-recyclerview

嗨,我正在创建一个聊天应用程序。应用程序正常。但是当收到新消息(通过后台服务)时,我会更新recylerview,然后用户必须向下滚动才能看到新消息。

我想要做的是,当收到新消息时,我想更新recyclerview并滚动到底部。这样,用户可以看到最后收到的消息,而无需滚动。

聊天活动

public class Chatting extends AppCompatActivity {


    private DrawerLayout drawerLayout;
    private ApplicationEnvironmentURL applicationEnvironment;
    private Toolbar toolbar;
    private SelectVisitorService mService = new SelectVisitorService();
    private boolean mBound = false;
    public static Context baseContext;

    private static String  uniqueID;
    public static ChattingAdapter mAdapter ;
    public static List<ChattingItomObject> messageItems = new ArrayList<ChattingItomObject>();
    private RecyclerView recyclerView;

    public String ProfileId;
    public String profileToken;
    public String CompanyID;
    public String DisplayName;

    public String visitor_id;
    public String visitor_name;

    private EditText chat_message;

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

        SharedPreferences prefs = getSharedPreferences("zupportdesk", MODE_PRIVATE);
        ProfileId = prefs.getString("ProfileId", "Not defined");
        profileToken = prefs.getString("profileToken", "Not defined");
        CompanyID = prefs.getString("companyId", "Not defined");
        DisplayName = prefs.getString("DisplayName", "Not defined");

        chat_message = (EditText) findViewById(R.id.ET_chating_message);
        baseContext = getBaseContext();

        Intent intent = getIntent();
        visitor_id = intent.getStringExtra("visitor_id");
        visitor_name = intent.getStringExtra("visitor_name");

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initNavigationDrawer();
        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle(visitor_name);

        uniqueID = UUID.randomUUID().toString();
        Log.d("GUIID", uniqueID);

        // add some items to list to test
        messageItems.add(new ChattingItomObject("VisitorID", visitor_name+" has joined the chat!", "", "Other", "UserName", "Other", uniqueID));
        messageItems.add(new ChattingItomObject("VisitorID", "Hi, how can I help you today?", "", "Other", "UserName", "Other", uniqueID));
        messageItems.add(new ChattingItomObject("VisitorID", DisplayName+" has joined the chat!", "", "Other", "UserName", "Other", uniqueID));

        recyclerView = (RecyclerView) findViewById(R.id.recycler_chat);
        mAdapter = new ChattingAdapter(this, messageItems);

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


    public static void updateChatting(String visitor_id, String message, String date_time, String operator_type, String visitor_name){

        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(Chatting.baseContext, notification);
        r.play();

        uniqueID = UUID.randomUUID().toString();
        Log.d("GUIID", uniqueID);

        messageItems.add(new ChattingItomObject(visitor_id, message, date_time, operator_type, visitor_name, "Message_Type", uniqueID));

        Handler refresh = new Handler(Looper.getMainLooper());
        refresh.post(new Runnable() {
            public void run(){mAdapter.notifyDataSetChanged();}
        });

    }

聊天适配器

public class ChattingAdapter extends RecyclerView.Adapter<ChattingViewHolders>{

    public List<ChattingItomObject> ChattingItem;
    private Context context;

    public ChattingAdapter(Context context, List<ChattingItomObject> items){
        this.ChattingItem = items;
        this.context = context;
    }

    @Override
    public ChattingViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {

        Log.d("ChattingAdapter", String.valueOf(viewType));
        if (viewType == 5001) {
            // self message
            View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_chat_operator, null);
            ChattingViewHolders rcv = new ChattingViewHolders(layoutView, context);
            Log.d("ChattingAdapter", String.valueOf(viewType)+" - Operator");
            return rcv;
        } else if(viewType == 5002) {
            // others message
            View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_chat_visitor, null);
            ChattingViewHolders rcv = new ChattingViewHolders(layoutView, context);
            Log.d("ChattingAdapter", String.valueOf(viewType)+" - visitor");
            return rcv;
        }else {
            View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_chat_other, null);
            ChattingViewHolders rcv = new ChattingViewHolders(layoutView, context);
            Log.d("ChattingAdapter", String.valueOf(viewType)+" - Other");
            return rcv;
        }
    }


    @Override
    public void onBindViewHolder(ChattingViewHolders holder, int position) {
        ChattingItomObject operator = ChattingItem.get(position);
        String operator_type = operator.getOperatorType().toString();
        Log.d("ChattingAdapter", "Message_type : "+operator_type);

        if(operator_type.equals("Operator")) {
            holder.operatorMessage.setText(ChattingItem.get(position).getMessage());
            holder.operatorTime.setText(ChattingItem.get(position).getDateTime());
        } else if(operator_type.equals("Visitor")){
            holder.visitorMessage.setText(ChattingItem.get(position).getMessage());
            holder.visitortime.setText(ChattingItem.get(position).getDateTime());
        } else {
            holder.otherMessage.setText(ChattingItem.get(position).getMessage());
        }
    }


    @Override
    public int getItemViewType(int position) {
        String message = ChattingItem.get(position).getOperatorType();
        if (message.equals("Operator")) {
            return 5001;
        } else if(message.equals("Visitor")){
            return 5002;
        }

        return position;
    }

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

查看持有人

public class ChattingViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{

    public TextView operatorMessage;
    public TextView operatorTime;
    public TextView visitorMessage;
    public TextView visitortime;
    public TextView otherMessage;
    private final Context context;

    public ChattingViewHolders(View itemView, Context context) {
        super(itemView);
        this.context = context;
        itemView.setOnClickListener(this);


        operatorMessage = (TextView) itemView.findViewById(R.id.CCO_message);
        operatorTime = (TextView) itemView.findViewById(R.id.CCo_time);
        visitorMessage = (TextView) itemView.findViewById(R.id.CCV_message);
        visitortime = (TextView) itemView.findViewById(R.id.CCV_time);
        otherMessage = (TextView) itemView.findViewById(R.id.CC_other_message);
    }

    @Override
    public void onClick(View view) {

    }
}

活动聊天XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    tools:context="zupportdesk.desk.zupport.chatsystem.Chatting">

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.learn2crack.myapplication.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:id="@+id/user_details_app_bar"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <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/AppTheme.PopupOverlay" />

               </android.support.design.widget.AppBarLayout>


                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/recycler_chat"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_alignParentTop="true"
                        android:layout_centerHorizontal="true"
                        android:scrollbars="none"
                        android:layout_marginTop="55dp"
                        android:layout_marginBottom="45dp" />

                            <RelativeLayout
                                android:layout_width="match_parent"
                                android:layout_height="50dp"
                                android:background="@color/colorPrimaryDark"
                                android:layout_alignParentBottom="true"
                                android:layout_alignParentLeft="true"
                                android:layout_alignParentStart="true">
                                <EditText
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:layout_weight="1"
                                    android:textColorHint="#CFD8DC"
                                    android:textColor="#CFD8DC"
                                    android:hint="Write a message"
                                    android:id="@+id/ET_chating_message"
                                    android:layout_alignParentBottom="true"
                                    android:layout_alignParentLeft="true"
                                    android:layout_alignParentStart="true"
                                    android:layout_toLeftOf="@+id/IV_Chatting_send"
                                    android:layout_toStartOf="@+id/IV_Chatting_send"
                                    android:layout_marginLeft="10dp" />

                                <ImageView
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:layout_weight="5"
                                    android:padding="4dp"
                                    android:onClick="send_chat_message"
                                    android:src="@android:drawable/ic_menu_send"
                                    android:id="@+id/IV_Chatting_send"
                                    android:layout_alignBottom="@+id/ET_chating_message"
                                    android:layout_alignParentRight="true"
                                    android:layout_alignParentEnd="true" />
                            </RelativeLayout>

                </RelativeLayout>


    </android.support.design.widget.CoordinatorLayout>


    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/menu_navigation"/>
</android.support.v4.widget.DrawerLayout>

有人可以帮助我在updateChatting方法中将Recyclerview滚动到底部。

4 个答案:

答案 0 :(得分:4)

notifyDataSetChanged()

之后调用此方法
recyclerView.scrollToPosition(mAdapter.getItemCount()-1);

此外,当您只向recyclerView添加新项目时,您可以致电notifyDataSetChanged()而不是致电mAdapter.notifyItemInserted(mAdapter.getItemCount()-1);

 public class ExifUtils {
 public Bitmap rotateBitmap(String src, Bitmap bitmap) {
    try {
        int orientation = getExifOrientation(src);

        if (orientation == 1) {
            return bitmap;
        }

        Matrix matrix = new Matrix();
        switch (orientation) {
            case 2:
                matrix.setScale(-1, 1);
                break;
            case 3:
                matrix.setRotate(180);
                break;
            case 4:
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case 5:
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case 6:
                matrix.setRotate(90);
                break;
            case 7:
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case 8:
                matrix.setRotate(-90);
                break;
            default:
                return bitmap;
        }

        try {
            Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle();
            return oriented;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return bitmap;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return bitmap;
}

private int getExifOrientation(String src) throws IOException {
    int orientation = 1;

    try {

        if (Build.VERSION.SDK_INT >= 5) {
            Class<?> exifClass = Class
                    .forName("android.media.ExifInterface");
            Constructor<?> exifConstructor = exifClass
                    .getConstructor(new Class[]{String.class});
            Object exifInstance = exifConstructor
                    .newInstance(new Object[]{src});
            Method getAttributeInt = exifClass.getMethod("getAttributeInt",
                    new Class[]{String.class, int.class});
            Field tagOrientationField = exifClass
                    .getField("TAG_ORIENTATION");
            String tagOrientation = (String) tagOrientationField.get(null);
            orientation = (Integer) getAttributeInt.invoke(exifInstance,
                    new Object[]{tagOrientation, 1});

        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (Fragment.InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (java.lang.InstantiationException e) {
        e.printStackTrace();
    }

    return orientation;
}

答案 1 :(得分:0)

向适配器添加新消息时。那个时候叫这个方法

recyclerViewObject.scrollToPosition(chatArrayList.size() - 1);

答案 2 :(得分:0)

在更新循环视图时调用它。

recyclerView.post(new Runnable() {
    @Override
    public void run() {

        recyclerView.smoothScrollToPosition(adapter.getItemCount());                                 
    }
});

答案 3 :(得分:0)

这最适合聊天应用程序。

 recyclerView.setAdapter(adapter);
 recyclerView.getAdapter().getItemCount();
 adapter.notifyDataSetChanged();
 recyclerView.getLayoutManager().scrollToPosition(user_arr.size() - 1);