先上效果圖:
我們可以直接在佈局中用RelativeLayout將ImageView和TextView包起來。也可以寫一個公用的佈局,用include標籤將佈局引入。但是爲了減少我們的代碼量,使之變得更簡單,我們可以寫一個自定義控件。如下:
public class TextMoreView extends FrameLayout {
private TextView mTvDesc;
private ImageView mIvMore,mIvImage;
public TextMoreView(Context context,AttributeSet attrs){
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.text_more_layout, this);
mTvDesc = (TextView) findViewById(R.id.text_more_desc);
mIvMore = (ImageView) findViewById(R.id.iv_more);
mIvImage = (ImageView) findViewById(R.id.iv_more_title);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TextMoreView);
String desc = array.getString(R.styleable.TextMoreView_desc);
Drawable drawable = array.getDrawable(R.styleable.TextMoreView_image);
mTvDesc.setText(desc);
mIvImage.setImageDrawable(drawable);
array.recycle();
}
public void setDescText(String desc){
mTvDesc.setText(desc);
}
public void setImage(Drawable drawable){
mIvImage.setImageDrawable(drawable);
}
public void setImageGone(){
mIvImage.setVisibility(GONE);
}
}
R.layout.text_more_layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@color/white"
android:layout_width="match_parent"
android:layout_height="46dp">
<ImageView
android:id="@+id/iv_more_title"
android:layout_width="28dp"
android:layout_height="28dp"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
/>
<TextView
android:id="@+id/text_more_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="@+id/iv_more_title"
android:text="wodo"
android:textColor="@color/custom_more_text"
android:textSize="@dimen/custom_more_view"/>
<ImageView
android:id="@+id/iv_more"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="15dp"
android:src="@drawable/selector_arrow_right"
/>
<View
android:layout_width="match_parent"
android:layout_height="0.6dp"
android:layout_alignParentBottom="true"
android:background="@color/talk_item_divider_line"
>
</View>
</RelativeLayout>
R.styleable.TextMoreView
在項目文件res/value下面創建一個attr.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextMoreView">
<attr name="desc" format="string"/>
<attr name="image" format="reference"></attr>
</declare-styleable>
</resources>
這裏的自定義屬性的format,可以有很多種:
- reference
- string
- color
- dimension
- boolean
- integer
- float
- fraction
- enum
- flag
然後在我們的佈局文件中使用的時候
要在跟佈局的位置添加以下代碼
xmlns:textMore="http://schemas.android.com/apk/res/com.lzx.iteam"
<com.my.widget.TextMoreView
android:id="@+id/tm_draft"
textMore:desc="草稿箱"
textMore:image="@drawable/function_draft"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</com.my.widget.TextMoreView>