1.自定义布局文件 rightmenu_item_layout.xml
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
android:id="@+id/menu_item_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:src="@drawable/ico_setting" />
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:src="@drawable/rightmenu_grey_point" />
android:id="@+id/menu_item_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:gravity="center_vertical|left"
android:textColor="@color/white"
android:textSize="36sp"
android:text="@string/str_setting" />
2.自定义布局类继承Layout RightMenuItemView.java
public class RightMenuItemView extends LinearLayout{
private Context mContext;
private ImageView itemIcon;
private TextView itemText;
public RightMenuItemView(Context context) {
this(context,null);
}
public RightMenuItemView(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
this.setFocusable(true);
View view = LayoutInflater.from(context).inflate(R.layout.rightmenu_item_layout,
this, true);
itemIcon = (ImageView)view.findViewById(R.id.menu_item_icon);
itemText = (TextView)view.findViewById(R.id.menu_item_text);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.RightMenuItemView);
CharSequence text = a.getText(R.styleable.RightMenuItemView_android_text);
if(text!=null)itemText.setText(text);
Drawable drawable = a.getDrawable(R.styleable.RightMenuItemView_android_src);
if(drawable != null) itemIcon.setImageDrawable(drawable);
a.recycle();
}
public void setImageResource(int resId) {
itemIcon.setImageResource(resId);
}
public void setItemText(String text) {
itemText.setText(text);
}
public void setItemTextSize(float size){
itemText.setTextSize(size);
}
public void setItemTextColor(int color){
itemText.setTextColor(color);
}
}
3.attrs
4.主代码中创建该View
RightMenuItemView itemBtn = new RightMenuItemView(mContext);
itemBtn.setItemTextSize(36);
itemBtn.setItemTextColor(getResources().getColor(R.color.white));
itemBtn.setItemText("测试");
itemBtn.setImageResource(R.drawable.xxx);