实现侧滑菜单的自定义属性配置
本文将介绍如何通过自定义属性来灵活控制侧滑菜单的显示宽度,从而避免直接修改代码带来的不便。我们将按照创建XML文件、在布局中使用以及在构造方法中获取值这三个步骤来进行说明。
首先,在Android开发中,为了满足特定UI需求,我们常常需要自定义组件样式。下面是如何为侧滑菜单添加一个自定义属性以调整其右侧填充。
XML文件(放置于res/values下的attrs.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="menuPaddingRight" format="dimension"/>
<declare-styleable name="CustomSlidingMenu">
<attr name="menuPaddingRight"/>
</declare-styleable>
</resources>
接下来是布局文件的应用示例:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.ui.CustomSlidingMenu
android:layout_width="match_parent"
android:layout_height="match_parent"
app:menuPaddingRight="80dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<include layout="@layout/left_panel"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"/>
</LinearLayout>
</com.example.ui.CustomSlidingMenu>
</RelativeLayout>
在自定义类的构造函数中获取设定值:
public CustomSlidingMenu(Context context) {
this(context, null);
}
public CustomSlidingMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomSlidingMenu(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CustomSlidingMenu, defStyleAttr, 0);
mPaddingRight = typedArray.getDimensionPixelSize(R.styleable.CustomSlidingMenu_menuPaddingRight, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 60, getResources().getDisplayMetrics()));
typedArray.recycle();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
screenWidth = metrics.widthPixels;
}
最终效果如下图所示:
