1、我们常见的效果如下:
如果不封装,每一次层的代码都是两个Textview,那么我们可以创建一个单独的View来简化代码。
自定义组合View的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@color/white"
android:layout_height="45dp">
<TextView
android:id="@+id/m_tv_ordername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:text="订单编号"
android:textColor="@color/text_bigtitle"
android:textSize="14sp" />
<TextView
android:id="@+id/m_tv_ordervalue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="15dp"
android:ellipsize="end"
android:maxLength="35"
android:singleLine="true"
android:text="1111"
android:textColor="@color/text_bigtitle"
android:textSize="14sp" />
</RelativeLayout>
效果如下:
2、开始编写自定义组合View,代码如下
分析:由于左侧的值是固定的,我们可以在布局中,直接写,方便浏览。
右侧的值是从服务器获取的,所以我们像textview.settext();一样去设置值。
public class OrderInfoView extends RelativeLayout {
TextView m_tv_ordername;
TextView m_tv_ordervalue;
public OrderInfoView(Context context) {
super(context);
initView(context);
}
public OrderInfoView(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.OrderInfoView);
m_tv_ordername.setText(ta.getString(R.styleable.OrderInfoView_leftname));
}
public OrderInfoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView(context);
}
private void initView(Context context) {
// TODO Auto-generated method stub
View.inflate(context, R.layout.m_orderinfo, this);
m_tv_ordername = (TextView) findViewById(R.id.m_tv_ordername);
m_tv_ordervalue = (TextView) findViewById(R.id.m_tv_ordervalue);
}
//设置内容
public void setMTVtext(String mvalue)
{
m_tv_ordervalue.setText(mvalue);
}
}
在value文件夹下,创建attrs.xml,定义自定义属性
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 订单详情自定义view-->
<declare-styleable name="OrderInfoView">
<attr name="leftname" format="string" /> <!-- format : 类型 -->
</declare-styleable>
</resources>
3、接下来就可以直接在我们的布局文件中调用了
注意,要在父布局加入命名空间的引入。