Android學習——利用RecyclerView編寫聊天界面

来源:http://www.cnblogs.com/cxq1126/archive/2017/07/17/7193228.html
-Advertisement-
Play Games

1、待會兒會用到RecyclerView,首先在app/build.gradle(註意有兩個build.gradle,選擇app下的那個)當中添加依賴庫,如下: 添加完之後記得點擊Sync Now進行同步。 2、開始編寫主界面,修改activity_main.xml中的代碼,如下: Recycler ...


1、待會兒會用到RecyclerView,首先在app/build.gradle(註意有兩個build.gradle,選擇app下的那個)當中添加依賴庫,如下:

1 dependencies {
2     compile fileTree(dir: 'libs', include: ['*.jar'])
3     compile 'com.android.support:appcompat-v7:24.2.1'
4     compile 'com.android.support:recyclerview-v7:24.2.1'
5     testCompile 'junit:junit:4.12'
6     androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
7         exclude group: 'com.android.support', module: 'support-annotations'
8     })
9 }

添加完之後記得點擊Sync Now進行同步。

2、開始編寫主界面,修改activity_main.xml中的代碼,如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:id="@+id/activity_main"
 4     android:orientation="vertical"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:background="#d8e0e8"
 8     >
 9     <android.support.v7.widget.RecyclerView
10         android:id="@+id/msg_recycler_view"
11         android:layout_width="match_parent"
12         android:layout_height="0dp"
13         android:layout_weight="1"
14         />
15     <LinearLayout
16         android:layout_width="match_parent"
17         android:layout_height="wrap_content">
18         <EditText
19             android:id="@+id/input_text"
20             android:layout_width="0dp"
21             android:layout_height="wrap_content"
22             android:layout_weight="1"
23             android:hint="Type something here"
24             android:maxLines="2"
25             />
26         <Button
27             android:id="@+id/send"
28             android:layout_width="wrap_content"
29             android:layout_height="wrap_content"
30             android:text="send"
31             />
32     </LinearLayout>
33 </LinearLayout>

RecyclerView用於顯示聊天的消息內容(因為不是內置在系統SDK中的,所以需要把完整的包路徑寫出來);

放置一個EditView用於輸入消息,一個Button用於發送消息。

3、定義消息的實體類,新建Msg,代碼如下:

 1 public class Msg {
 2     public static final int TYPE_RECEIVED=0;
 3     public static final int TYPE_SENT=1;
 4     private String content;
 5     private int type;
 6     public Msg(String content,int type){
 7         this.content=content;
 8         this.type=type;
 9     }
10     public String getContent(){
11         return content;
12     }
13 
14     public int getType(){
15         return type;
16     }
17 }

Msg只有兩個欄位,content表示消息的內容,type表示消息的類型(二值可選,一個是TYPE_RECRIVED,一個是TYPE_SENT)。

4、接著編寫RecyclerView子項的佈局,新建msg_item.xml,代碼如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="wrap_content"
 6     android:padding="10dp"
 7     >
 8 
 9     <LinearLayout
10         android:id="@+id/left_layout"
11         android:layout_width="283dp"
12         android:layout_height="106dp"
13         android:layout_gravity="left"
14         android:background="@drawable/zuo"
15         android:weightSum="1">
16 
17         <TextView
18             android:id="@+id/left_msg"
19             android:layout_width="match_parent"
20             android:layout_height="wrap_content"
21             android:layout_gravity="center"
22             android:layout_margin="10dp"
23             />
24     </LinearLayout>
25 
26     <LinearLayout
27         android:id="@+id/right_layout"
28         android:layout_width="229dp"
29         android:layout_height="109dp"
30         android:layout_gravity="right"
31         android:background="@drawable/you"
32         >
33         <TextView
34             android:id="@+id/right_msg"
35             android:layout_width="wrap_content"
36             android:layout_height="wrap_content"
37             android:layout_gravity="center"
38             android:layout_margin="10dp"
39             />
40     </LinearLayout>
41 
42 </LinearLayout>

收到的消息局左對齊,發出的消息居右對齊,並用相應的圖片作為背景。

5、創建RecyclerView的適配器類,新建MsgAdapter,代碼如下:

 1 public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
 2     private List<Msg> mMsgList;
 3     static class ViewHolder extends RecyclerView.ViewHolder{
 4         LinearLayout leftLayout;
 5         LinearLayout rightLayout;
 6         TextView leftMsg;
 7         TextView rightMsg;
 8         public ViewHolder(View view){
 9             super(view);
10             leftLayout=(LinearLayout)view.findViewById(R.id.left_layout);
11             rightLayout=(LinearLayout)view.findViewById(R.id.right_layout);
12             leftMsg=(TextView)view.findViewById(R.id.left_msg);
13             rightMsg=(TextView)view.findViewById(R.id.right_msg);
14         }
15     }
16     public MsgAdapter(List<Msg> msgList){
17         mMsgList=msgList;
18     }
19     @Override
20     public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){               //onCreateViewHolder()用於創建ViewHolder實例
21         View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
22         return new ViewHolder(view);                                                   //把載入出來的佈局傳到構造函數中,再返回
23     }
24     @Override
25     public void onBindViewHolder(ViewHolder Holder,int position){                     //onBindViewHolder()用於對RecyclerView子項的數據進行賦值,會在每個子項被滾動到屏幕內的時候執行
26         Msg msg=mMsgList.get(position);
27         if(msg.getType()==Msg.TYPE_RECEIVED){                                         //增加對消息類的判斷,如果這條消息是收到的,顯示左邊佈局,是發出的,顯示右邊佈局
28             Holder.leftLayout.setVisibility(View.VISIBLE);
29             Holder.rightLayout.setVisibility(View.GONE);
30             Holder.leftMsg.setText(msg.getContent());
31         }else if(msg.getType()==Msg.TYPE_SENT) {
32             Holder.rightLayout.setVisibility(View.VISIBLE);
33             Holder.leftLayout.setVisibility(View.GONE);
34             Holder.rightMsg.setText(msg.getContent());
35         }
36     }
37     @Override
38     public int getItemCount(){
39         return mMsgList.size();
40     }
41 }

6、最後修改MainActivity中的代碼,來為RecyclerView初始化一些數據,並給發送按鈕加入事件響應,代碼如下:

 1 public class MainActivity extends AppCompatActivity {
 2     private List<Msg> msgList=new ArrayList<>();
 3     private EditText inputText;
 4     private Button send;
 5     private RecyclerView msgRecyclerView;
 6     private MsgAdapter adapter;
 7 
 8     @Override
 9     protected void onCreate(Bundle savedInstanceState) {
10         super.onCreate(savedInstanceState);
11         setContentView(R.layout.activity_main);
12         initMsgs();                                                         //初始化消息數據
13         inputText=(EditText)findViewById(R.id.input_text);
14         send=(Button)findViewById(R.id.send);
15         msgRecyclerView=(RecyclerView)findViewById(R.id.msg_recycler_view);
16 
17         LinearLayoutManager layoutManager=new LinearLayoutManager(this);    //LinearLayoutLayout即線性佈局,創建對象後把它設置到RecyclerView當中
18         msgRecyclerView.setLayoutManager(layoutManager);
19 
20         adapter=new MsgAdapter(msgList);                                    //創建MsgAdapter的實例並將數據傳入到MsgAdapter的構造函數中
21         msgRecyclerView.setAdapter(adapter);
22 
23         send.setOnClickListener(new View.OnClickListener(){                 //發送按鈕點擊事件
24             @Override
25             public void onClick(View v){
26                 String content=inputText.getText().toString();              //獲取EditText中的內容
27                 if(!"".equals(content)){                                    //內容不為空則創建一個新的Msg對象,並把它添加到msgList列表中
28                     Msg msg=new Msg(content,Msg.TYPE_SENT);
29                     msgList.add(msg);
30                     adapter.notifyItemInserted(msgList.size()-1);           //調用適配器的notifyItemInserted()用於通知列表有新的數據插入,這樣新增的一條消息才能在RecyclerView中顯示
31 msgRecyclerView.scrollToPosition(msgList.size()-1); //調用scrollToPosition()方法將顯示的數據定位到最後一行,以保證可以看到最後發出的一條消息 32 inputText.setText(""); //調用EditText的setText()方法將輸入的內容清空 33 } 34 } 35 }); 36 } 37 38 private void initMsgs(){ 39 Msg msg1=new Msg("Hello guy.",Msg.TYPE_RECEIVED); 40 msgList.add(msg1); 41 Msg msg2=new Msg("Hello.Who is that?",Msg.TYPE_SENT); 42 msgList.add(msg2); 43 Msg msg3=new Msg("This is Tom!",Msg.TYPE_RECEIVED); 44 msgList.add(msg3); 45 } 46 }

運行程式,效果如下:


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • `SVProgressHUD iOS`開發中比較常用的一個三方庫,用來在執行耗時操作或者指示用戶操作結果的場合,由於使用簡單,功能豐富,交互友好,被廣泛應用。本文從源碼的角度,解讀一下實現的過程,希望能起到拋磚引玉的作用。 一. 效果預覽 1. SVPIndefiniteAnimatedView 2 ...
  • 思路:獲取每項item的高度,並相加,再加上分割線的高度,作為整個ListView的高度,方法如下: ...
  • 說明:這篇文章是在百度上搜索“NSURLSession與NSURLConnection區別”查找到的資料,僅供自己學習理解,不屬於原創,本來想註明來源,但是發現很多內容相同的文章,也不知道誰才是真正的原創作者,所以就不寫明出處了!在這裡我向真正的原作者說聲感謝,謝謝你的分享! 1、 使用現狀 NSU ...
  • JB2/JB3/JB5/JB9版本: 1. 請修改 Launcher2/res/layout/qsb_bar.xml,如下:<include android:id="@+id/qsb_search_bar"layout="@layout/search_bar"android:visibility=" ...
  • 一、碎片的簡單用法(實現在一個活動中添加兩個碎片,並讓這兩個碎片平分活動空間) 1、新建一個FragmentTest項目; 新建一個左側碎片佈局left_fragment.xml,代碼如下:(只放置一個按鈕並水平居中顯示) 新建右側碎片佈局right_fragment.xml,代碼如下:(佈局背景設 ...
  • Android Studio 生成 Java Doc 出現“編碼GBK的不可映射字元”問題 錯誤的解決方案,複製粘貼一萬遍也是錯誤的,下麵是查找出來的,沒有用的解決方案(還有幾個,就例舉下麵這個): 這種坑人的、自己沒有試過的、浪費大家時間的方案就不要轉發了好嗎?不要轉發了好嗎?不要轉發了好嗎? 正 ...
  • 一、傳值分類 頁面傳值基本分為兩種:正向傳值和反向傳值。 二、傳值方式 傳值,最基本的無非就是代理傳值、通知傳值、block傳值等,還有大家經常用到的屬性傳值和單例傳值、存儲傳值等。 1、代理傳值 代理傳值,簡單明瞭、淺顯易懂,實際開發中也常用。 委托做的事情: 1.1、聲明委托變數 1.2 定義協 ...
  • 之前的文章,在上面建立完config之後,UIl通過 來初始化ImageLoader對象,之後就可以用ImageLoader來載入圖片。 這裡,採用到單例模式來獲取ImageLoader對象,保證他全局初始化一次。再上面的分析中,我們可以看出單例模式的好處,創建ImageLoader對象的時候需要創 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...