多布局
什么是多布局?
图例:
多布局就是实现像qq或者微信这样的聊天页面
首先要写两个布局
左布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ImageView
android:id="@+id/head"
android:layout_width="40dp"
android:layout_height="40dp" />
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18dp"/>
</LinearLayout>
右布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<ImageView
android:id="@+id/head"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"/>
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/head"
android:textSize="18dp"
/>
</RelativeLayout>
咱们在这里简单的布一下局,主要看效果
就只用了一个图片、一个文本显示
然后就是适配器的设置了
在这里,我们需要使用优化的ListView适配
代码如下:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view ;
if(convertView==null){
view=new ViewHolder();
if(chats.get(position).getId()%2==1){
convertView = View.inflate(context,R.layout.left_layout,null);
}else if(chats.get(position).getId()%2==0){
convertView = View.inflate(context,R.layout.right_layout,null);
}
view.head = convertView.findViewById(R.id.head);
view.message = convertView.findViewById(R.id.message);
convertView.setTag(view);
}else{
view= (ViewHolder) convertView.getTag();
}
view.message.setText(chats.get(position).getMessage());
if(chats.get(position).getId()%2==1){
Glide.with(context).load(R.mipmap.touxiang).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(view.head);
}else if(chats.get(position).getId()%2==0){
Glide.with(context).load(R.mipmap.yaya).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(view.head);
}
return convertView;
}
public class ViewHolder{
ImageView head;
TextView message;
}
为了把布局中的控件拿到,写一个内部类,来写控件
通过判断convertView是否为空,在判断是否创建这个类,如果convertView为空,把ViewHolder创建出来,并且给converView设置布局,然后我们在发来的集合中判断一个标记,如果通过标记来判断用左布局还是右布局,把viewHolder中的控件通过id拿到,给它们设置内容,最后加一个convertView.setTag(view);如果convertView不为空,直接给viewHolder设置为convertView.getTag();这里需要强制转换一下.
当把这些都完成之后,需要重写两个方法
@Override
public int getItemViewType(int position) {
return chats.get(position).getId();
}
@Override
public int getViewTypeCount() {
return 2;
}
第一个方法是获得集合中的标记,第二个方法是只能有两个标记
如果不写这两方法,可能会导致布局错乱,所以必须写这两个方法。
温馨提示:标记只能是 0和1,因为重写了getView.TypeCount() 这个方法