android开发页面可能会有如下场景: 「 一个listview的item会有多种样式,但是有些是一成不变的,比如说聊天界面:我可以发送图片,文字,视频。但是我的头像,名字是不会变的。也就是说发送内容是变化的,发送者的信息是不变的。 」 那么如何让发送者信息是一个layout(并且复用),而发送者内容是另一个layout(重新写)。 如下解决: 讲发送的信息作为一个layout,而内容方面留出一个view占用,类似于fragment的。 代码如下message_item_content则是占用代码(这个是要复用的layout)
<?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:orientation="horizontal" android:padding="6dp"> <com.view.HeadImageView android:layout_width="50dp" android:layout_height="50dp" android:id="@+id/lefthead" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <LinearLayout android:orientation="horizontal" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_centerHorizontal="true"> <ImageView android:id="@+id/message_item_alert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginLeft="2dp" android:layout_marginRight="2dp" android:src="@mipmap/ic_failed" android:visibility="visible" /> <FrameLayout android:id="@+id/message_item_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@android:color/transparent" /> </LinearLayout> <com.view.HeadImageView android:layout_width="50dp" android:layout_height="50dp" android:id="@+id/righthead" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /></LinearLayout>之后创建一个text的layout(就不写代码了)
创建好了之后,如何将text的layout嵌入到要复用的layout呢? 如下代码展示
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message_item, null); FrameLayout contentContainer = (FrameLayout)view.findViewById(R.id.message_item_content); View.inflate(view.getContext(), R.layout.message_item_text, contentContainer);如上嵌入成功!!
新闻热点
疑难解答