第11天EventBus和Otto第三方框架
优化聊天布局
一.EventBus介绍:
EventBus能够简化各组件间的通信,让我们的代码书写变得简单,能有效的分离事件发送方和接收方(也就是解耦的意思)。
二.EventBus三大要素
Event 事件。它可以是任意类型。
Subscriber 事件订阅者。
Publisher 事件的发布者。我们可以在任意线程里发布事件,一般情况下,使用EventBus.getDefault()就可以得到一个EventBus对象,然后再调用post(Object)方法即可。
三.EventBus四种线程模型
POSTING (默认) 表示事件处理函数的线程跟发布事件的线程在同一个线程。
MAIN 表示事件处理函数的线程在主线程(UI)线程,因此在这里不能进行耗时操作。
BACKGROUND 表示事件处理函数的线程在后台线程,因此不能进行UI操作。如果发布事件的线程是主线程(UI线程),那么事件处理函数将会开启一个后台线程,如果果发布事件的线程是在后台线程,那么事件处理函数就使用该线程。
ASYNC 表示无论事件发布的线程是哪一个,事件处理函数始终会新建一个子线程运行,同样不能进行UI操作。
添加依赖
implementation 'org.greenrobot:eventbus:3.0.0'
注册和解除注册+声明订阅者+事件发布
分别在Activity的onCreate()方法和onDestory()方法里,进行注册EventBus和解除注册。
代码如下
public class FirstActivity extends AppCompatActivity {
private Button mButton;
private TextView mText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
mButton = (Button) findViewById(R.id.btn1);
mText = (TextView) findViewById(R.id.tv1);
//注册
EventBus.getDefault().register(this);
//发布事件
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EventBus.getDefault().post(new MessageEvent("欢迎大家浏览我写的博客"));
}
});
}
//声明订阅者
@Subscribe(threadMode = ThreadMode.MAIN)
public void Event(MessageEvent messageEvent) {
mText.setText(messageEvent.getMessage());
}
//解除注册
@Override
protected void onDestroy() {
super.onDestroy();
if(EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
}
}
Otto第三方框架
代码如下
依赖 implementation 'com.squareup:otto:1.3.8'
定义一个类 AppBus, 继承Bus , ---- 单例模式 , 返回Bus 的子类对象
注册到Bus 的主线程中
AppBus.getInstance().register(this);
在onDestry() 方法中取消注册
@Override
protected void onDestroy() {
super.onDestroy();
AppBus.getInstance().unregister(this);
}
声明订阅者
@Subscribe
public void receiveMessage(String result)
{
Toast.makeText(this, "result = " + result, Toast.LENGTH_SHORT).show();
}
发起订阅 -- 主线程中
AppBus.getInstance().post("OTTO 返回的数据");
优化聊天布局
重写两个方法
@Override
public int getItemViewType(int position) {
return (int)list.get(position).get("flag");
}
@Override
public int getViewTypeCount() {
return 2;
}
getivew中的优化
public View getView(int position, View convertView, ViewGroup parent) {
Hello hello;
if(convertView==null) {
hello = new Hello();
if (getItemViewType(position)== 0) {
convertView= LayoutInflater.from(mainActivity).inflate(R.layout.layout2,null);
} else{
convertView= LayoutInflater.from(mainActivity).inflate(R.layout.layout3,null);
}
convertView.setTag(hello);
}else {
hello= (Hello) convertView.getTag();
}
hello.textView=convertView.findViewById(R.id.a2);
hello.textView.setText(list.get(position).get("mess").toString());
return convertView;
}