先上效果图:
我们可以直接在布局中用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); } }
<?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,可以有很多种:
然后在我们的布局文件中使用的时候
要在跟布局的位置添加以下代码
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>