03UI開發-RecyclerView及簡單聊天界面

基本用法

  1. 想要使用這個控件,首先在項目的build.gradle中添加相應的依賴庫才行
    打開app/build.gradle文件,在dependencies閉包中添加
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    // 添加的是這一句
    compile 'com.android.support:recyclerview-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

  1. 添加完成后點擊一下Sync Now來進行同步,然后修改activity_main.xml中的代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view_1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

添加一個控件,寬度和高度都是占滿整部布局空間的

  1. 接下來定義一個自定義布局fruit_item.xml,這個時候注意layout_width="wrap_content"的設置,讓它自適應大就可以了
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="20dp"
        />

</LinearLayout>

4.定義一個實體類,作為RecyclerView適配器的適配類型,建立Fruit


public class Fruit {
    private String name;
    private int imageId;

    public Fruit(String name,int imageId){
        this.imageId = imageId;
        this.name = name;
    }
    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }
}

  1. 為RecyclerView準備一個適配器,新建FruitAdapter類,讓這個適配器繼承RecyclerView.Adapter,并將泛型指定為FruitAdapter.ViewHolder,其中ViewHolder是我們在FruitAdapter中定義的一個內部類

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

    private List<Fruit> mFruitList;

    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(View view){
            super(view);
            fruitImage=(ImageView)view.findViewById(R.id.img);
            fruitName = (TextView)view.findViewById(R.id.text);
        }
    }

    public FruitAdapter(List<Fruit> fruitList){
        mFruitList = fruitList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

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


}


  • 首先定義了一個內部類,ViewHolder要繼承自RecyclerView.ViewHolder,然后在這個里面的構造函數中傳入了一個View參數,這個參數通常就是RecyclerView子項的最外層布局,那么就可以通過這個findViewById()的方法獲取到布局中的ImageVIew和TextView的實例了
  • FruitAdapter中也有一個構造函數,這個函數用于將把要展示的數據源傳遞進來,并賦值給一個全局變量mFruitList,后面操作的就是這個數據源了
  • 由于FruitAdapter繼承自RecyclerView.Adapter,那么就必須重寫 onCreateViewHolder(),onBindViewHolder(),getItemCount()這三個方法,
  • onCreateViewHolder()方法用于創建一個ViewHolder實例,并把加載出來的布局傳入到構造函數中,最后將ViewHolder的實例返回
  • onBindViewHolder()方法用與對RecyclerView子項的數據進行賦值,會在每個子項滾動到屏幕內的時候執行,通過position參數可以獲得當前項的Fruit實例,然后再將數據設置到ViewHolder的ImageView和TextVIew中
  • getItemCount()用于告訴RecyclerVIew一共有多少個子項,直接返回數據源的長度
  1. 接下來就可以使用RecyclerView,修改MainActivity中的代碼

public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 用于初始化水果
        initFruits();
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view_1);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }


    private void initFruits(){
        for (int i= 0;i<2;i++){
            Fruit apple = new Fruit("Apple",R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana",R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit("orange",R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit watermelon = new Fruit("watermelon",R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit("pear",R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit("grape",R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("pineapple",R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit("strawberry",R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit("cherry",R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit("mango",R.drawable.mango_pic);
            fruitList.add(mango);
        }
    }

}

  • 使用了同樣的initFruits()方法,用于初始化水果的數據,接著onCreate()方法獲取到RecyclerView的實例,
  • 創建一個LayoutManager用于指定RecycleView的布局方式,這里使用的是LinearLayoutManager是線性布局的意思,可以實現和ListView類似的效果,
  • 接下來創建一個FruitAdapter的實例,將水果的數據傳入到FruitAdapter的構造函數中
  • 最后調用RecyclerView的setAdapter()方法來完成適配器的設置,這樣RecyclerVIew和數據之間的關聯就建立完成了


    2018-03-11_16-06-47.png

實現橫向滾動和瀑布流布局

  1. 首先要對fruit_item布局進行修改,實現橫向滾動,得把這里面的元素改成垂直排列的方式
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="100dp"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        />

</LinearLayout>

  • android:orientation="vertical"該成了垂直方向排列,而且寬度色設置為100dp,這樣不會因為每種水果名字的長度不一而導致RecycleView的各個子項長短不一
  • android:layout_gravity="center_horizontal" 都設置為水平居中
  1. 修改MainActivity中的代碼
package com.example.md.recyclerview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

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

public class MainActivity extends AppCompatActivity {


    private List<Fruit> fruitList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 用于初始化水果
        initFruits();
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view_1);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        // 多添加這一句話
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }
        
    ..............

}


  • 相比之下,只多了一行代碼,調用了layoutManager的setOrientation()方法來設置布局的排列方法,默認是縱向的,傳入LinearLayoutManager.HORIZONTAL表示讓布局橫向排列
    Snipaste_2018-03-11_16-20-07.png
  1. 除了LinearLayoutManager之外,RecyclerView還提供了GridLayoutManagerStaggeredGridLayoutManager這樣中內置的布局排列方式,GridLayoutManager是用于網絡布局,StaggeredGridLayoutManager用于瀑布布局
    修改fruit_item.xml中的代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp">

    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:layout_marginTop="20dp"
        />

</LinearLayout>

只有幾處調整,把寬度有100dp改成match_parent,因為瀑布的寬度是根據布局的列數自動匹配的,不是一個固定的值,還用margin屬性,讓子項之間留點間距,文字的對齊方式改成了左對齊

  1. 修改MainActivity中的代碼

public class MainActivity extends AppCompatActivity {


    private List<Fruit> fruitList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 用于初始化水果
        initFruits();
        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view_1);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        // 多添加這一句話
//        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

//      主要就是這一行代碼,瀑布
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(
                3, StaggeredGridLayoutManager.VERTICAL
        );

        // 網絡
        //GridLayoutManager layoutManager = new GridLayoutManager(this,4);

        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

    private void initFruits(){
        for (int i= 0;i<2;i++){
            Fruit apple = new Fruit(getRandomLengthName("Apple"),R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit(getRandomLengthName("Banana"),R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit(getRandomLengthName("orange"),R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit watermelon = new Fruit(getRandomLengthName("watermelon"),R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit(getRandomLengthName("pear"),R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit(getRandomLengthName("grape"),R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit(getRandomLengthName("pineapple"),R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit(getRandomLengthName("strawberry"),R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit(getRandomLengthName("cherry"),R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit(getRandomLengthName("mango"),R.drawable.mango_pic);
            fruitList.add(mango);
        }
    }

// 不想實現也可以不用寫
    private String getRandomLengthName(String name){
        Random random = new Random();
        int length = random.nextInt(20) + 1;
        StringBuilder builder = new StringBuilder();
        for(int i = 0;i<length;i++){
            builder.append(name);
        }
        return builder.toString();
    }

}

  • 首先在onCreate()方法中,創建了StaggeredGridLayoutManager的實例,它的構造函數接收了兩個參數,第一個用于指定布局的列數,傳入3表示會把布局分為3列,第二個參數用于指定布局的排列方向, StaggeredGridLayoutManager.VERTICAL表示是縱向排列,最后再把創建好的實例設置到RecyclerView中
  • 這里使用了一個小技巧,在這個getRandomLengthName()方法上,這個方法用了Random對象來創造一個1到20之間的隨機數,然后將參數中傳入的字符重復隨即便,在initFruits()方法中,每個水果的名字都調用這個方法來生成,這樣就保證水果的名字的長短差距大,子項的高度就不一樣了


    2018-03-11_16-45-14.png
  • 若不寫這個方法也是可以的,在傳入的時候直接寫入水果的名字也可以


    2018-03-17_11-13-27.png
  • 當然了,還可以寫網絡布局,只需要創建一個GridLayoutManager實例就可以了,它的構造函數接收兩個參數,第一個是上下文對象,第二個參數是一行顯示幾列數據


    2018-03-17_11-19-17.png

RecyclerView的點擊事件

這個的注冊監聽器方法是需要我們自己給子項具體的View去注冊點擊事件的

  1. 修改FruitAdapter中的代碼

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

    private List<Fruit> mFruitList;

    static class ViewHolder extends RecyclerView.ViewHolder{
        // 這里定義一個View變量
        View fruitView;
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder(View view){
            super(view);
            // 保存最外層的布局實例
            fruitView  = view;
            fruitImage = view.findViewById(R.id.img);
            fruitName = view.findViewById(R.id.text);
        }
    }

    public FruitAdapter(List<Fruit> fruitList){
        mFruitList = fruitList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
       // 
        final ViewHolder holder = new ViewHolder(view);

        //分別為最外層的布局和Image注冊點擊事件
        holder.fruitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 獲取到position,然后拿到Fruit實例
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"you click view"+fruit.getName(),Toast.LENGTH_SHORT).show();
            }
        });
        holder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(v.getContext(),"you clcik image"+fruit.getImageId(),Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

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

  • 先修改ViewHolder,在ViewHolder中添加fruitView變量來保存子項最外層布局的實例,然后在onCreateViewHolder()方法中注冊點擊事件
  • 分別為最外層的布局和Image都注冊了事件,先獲取到用戶點擊的position,然后通過position拿到響應的Fruit實例,然后通過Toast顯示


    點擊圖片.png

    點擊文字.png

了解Nine-Patch

  1. 現在項目中有一個氣泡狀的圖片,將這個圖片設置為背景圖片
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/beijing"
    >
</LinearLayout>

2018-03-17_13-53-54.png

這個時候可以看到圖片被均勻的拉伸了,效果極差,這個時候就可以使用Nine-Patch來處理了

  1. 右擊要添加的圖片,點擊Create 9-Patch file


    2018-03-17_13-55-30.png
  2. 就進入到這個頁面


    2018-03-17_13-57-25.png

    我們可以在四周繪制一個個小黑點,按住Shift鍵拖動就可以進行擦除,使用這個新的圖片替換原來的,再運行程序就可以看到


    2018-03-17_14-00-18.png
  3. 這樣,當圖片需要拉伸的時候,就指定拉伸的區域,在外觀上就好看了

編寫聊天界面

  1. 首先使用到的是RecyclerView,所以首先進行在app/build.gradle中添加依賴庫
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    // 添加這行代碼
    compile 'com.android.support:recyclerview-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

  1. 編寫主頁面,修改activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d8e0e8"
    >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyc_1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/edit_1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="Type something here"
            android:textSize="25sp"
            android:maxLines="2"/>

        <Button
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:text="Send"/>

    </LinearLayout>



</LinearLayout>

  • 在主頁面中放一個RecycleView用于顯示聊天的消息內容,又放置了一個輸入框,和一個按鈕
  1. 定義消息的實體類,新建一個Msg
public class Msg {
    // 接收到一條消息
    public static final int TYPE_RECEVED = 0;
    // 發出一條消息
    public static final int TYPE_SENT = 1;

    //消息內容
    private String content;
    // 消息類型
    private int type;

    public Msg(String content,int type){
        this.content = content;
        this.type = type;
    }
    public String getContent(){
        return content;
    }
    public int getType(){
        return type;
    }
}

  • Msg中只有兩個字段,content表示消息的內容,type表示消息的類型,其中消息的類型有兩個值可選,一個是TYPE_RECEVED表示接收到的數據,TYPE_SENT表示發送的數據
  1. 接下來編寫RecyclerView的子項布局,新建msg_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/left_layout"
        android:layout_gravity="left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/message_left">

        <TextView
            android:id="@+id/left_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:textColor="#fff"
            android:textSize="25sp"/>

    </LinearLayout>


    <LinearLayout
        android:id="@+id/right_layout"
        android:layout_gravity="right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/message_right">

        <TextView
            android:id="@+id/right_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:textColor="#000000"
            android:textSize="25sp"/>

    </LinearLayout>


</LinearLayout>

  • 接收到的消息左對齊,發送的消息右對齊,這個時候問題來了,怎么讓收到的消息和發出的消息在一個布局中呢在這一個布局中,必定有一個控件是空白的在學基本控件的時候學到了可見屬性,稍后在代碼中可以根據這個消息的類型來決定隱藏和顯示那種消息
  1. 編寫自定義的MagAdapter適配器,和在RecyclerView寫的適配器代碼基本一樣

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

    private List<Msg> mMsgList;

    static class ViewHolder extends RecyclerView.ViewHolder{

        LinearLayout leftLayout;
        LinearLayout rightLayout;
        TextView lefMsg;
        TextView rightMsg;

        public ViewHolder(View itemView) {
            super(itemView);
            leftLayout = (LinearLayout)itemView.findViewById(R.id.left_layout);
            rightLayout = (LinearLayout)itemView.findViewById(R.id.right_layout);
            lefMsg = (TextView)itemView.findViewById(R.id.left_msg);
            rightMsg = (TextView)itemView.findViewById(R.id.right_msg);
        }

    }

    public MsgAdapter(List<Msg> msgList){
        mMsgList = msgList;
    }

    @Override
    public MsgAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MsgAdapter.ViewHolder holder, int position) {
        Msg msg = mMsgList.get(position);
        if (msg.getType() == Msg.TYPE_RECEVED){
            // 如果是接收到的消息,則顯示左邊的消息布局,將右邊的隱藏
            holder.leftLayout.setVisibility(View.VISIBLE);
            holder.rightLayout.setVisibility(View.GONE);
            holder.lefMsg.setText(msg.getContent());
        }else if (msg.getType() == Msg.TYPE_SENT){
            // 如果是發送消息,那么顯示右邊的布局,把左邊的布局隱藏
            holder.rightLayout.setVisibility(View.VISIBLE);
            holder.leftLayout.setVisibility(View.GONE);
            holder.rightMsg.setText(msg.getContent());
        }
    }

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


  1. 修改MainActivity中的代碼

public class MainActivity extends AppCompatActivity {

    private List<Msg> msgList = new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        // 初始化消息數據
        initMsag();
        inputText = (EditText)findViewById(R.id.edit_1);
        send = (Button)findViewById(R.id.send);
        // 獲取到這個滾動控件
        msgRecyclerView = (RecyclerView)findViewById(R.id.recyc_1);
        // 指定這個控件的布局方式
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //設置到這個滾動控件中
        msgRecyclerView.setLayoutManager(layoutManager);
        // 數據傳入到自定義的適配器中
        adapter = new MsgAdapter(msgList);
        msgRecyclerView.setAdapter(adapter);
        //點擊按鈕的時候
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 獲取到消息框中的內容
                String content = inputText.getText().toString();
                if (!"".equals(content)){
                    Msg msg = new Msg(content,Msg.TYPE_SENT);
                    msgList.add(msg);
                    // 當有新的消息的時候刷新ListView中的顯示
                    adapter.notifyItemInserted(msgList.size()-1);
                    // 將ListView定位到最后一行
                    msgRecyclerView.scrollToPosition(msgList.size()-1);
                    // 清空輸入框中的內容
                    inputText.setText("");
                }
            }
        });


    }

    public void initMsag(){
        Msg msg = new Msg("hello pony",Msg.TYPE_RECEVED);
        msgList.add(msg);
        Msg msg1 = new Msg("hello Tom",Msg.TYPE_SENT);
        msgList.add(msg1);
        Msg msg2 = new Msg("我們去哪里呀?",Msg.TYPE_RECEVED);
        msgList.add(msg2);
    }
}


  • 在initMsag()中初始化了幾條數據,用于在RecyclerView中顯示
  • 在點擊按鈕的時候,如果內容不為空,就創建了一個Msg對象,并且添加到了msgList中去
  • 然后調用適配器的notifyItemInserted()方法,用于通知列表中有新的數據插入,這樣新增的一條消息才能夠在RecyclerVIew中顯示,
  • 接著調用RecyclerView的scrollToPosition()方法,將數據定位到最后一行,
  • 最后調用setTExt()方法將輸入的內容清空


    2018-03-17_16-13-25.png

參考數據:第一行代碼
若有錯誤請指出

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,197評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,415評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,104評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,884評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,647評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,130評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,208評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,366評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,887評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,737評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,478評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,174評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,586評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,827評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,608評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,914評論 2 372

推薦閱讀更多精彩內容