在App開發過程中,通常會遇到向這樣的佈局(如下圖),說設計起來也不麻煩,不錯經常寫起來也挺煩的;
爲了以後開發方便,自定義了一個這樣的通用的樣式,每次寫時,只需要引入對應的樣式就可.
首先要自定義一個view,爲了簡單起見,通常是繼承RelativeLayout(LinearLayout 等也可),複寫構成函數,並初始化自己要塞的佈局;
public class TextViewClickUi extends RelativeLayout {
private TextView itemName;
private String namespace = "http://schemas.android.com/apk/res/cn.liujigang.mobilefragment";
private String text;
public TextViewClickUi(Context context) {
super(context);
init(context);
}
public TextViewClickUi(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
text = attrs.getAttributeValue(namespace, "text");
itemName.setText(text);
}
public TextViewClickUi(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
text = attrs.getAttributeValue(namespace, "text");
itemName.setText(text);
}
private void init(Context context) {
View view = View.inflate(context, R.layout.view_textview_clickui, this);
itemName = (TextView) view.findViewById(R.id.tv_click_textview);
}
public void setText(CharSequence text) {
itemName.setText(text);
}
}
init函數中,初始化要顯示的佈局<?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="wrap_content"
android:background="@drawable/select_item_thrid"
android:clickable="true"
android:focusable="true" >
<TextView
android:id="@+id/tv_click_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingBottom="12dip"
android:paddingLeft="10dip"
android:paddingTop="12dip"
android:textColor="@android:color/black"
android:textSize="15sp" />
<ImageView
android:layout_width="8.0dip"
android:layout_height="16.0dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="7dip"
android:contentDescription="@null"
android:src="@drawable/ljg_more" />
</RelativeLayout>
具體代碼中的應用
<cn.liujigang.mobilefragment.widget.TextViewClickUi
android:id="@+id/tvcu_share"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tvit:text="分享給朋友" />
注意:要在根佈局中添加約束,eg:xmlns:tvit="http://schemas.android.com/apk/res/cn.liujigang.mobilefragment"
該約束要和自定義的自定義一個view中的namespace要保持一致.約束的後綴是你的AndroidManifest.xml中的package值一致;
對了還有一點就是:需要在values中的attrs.xml中添加上
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SettingView">
<attr name="text" format="string" />
</declare-styleable>
</resources>