QQ左侧滑动显示之自定义属性

时间:2023-03-09 15:29:44
QQ左侧滑动显示之自定义属性

  上一篇为大家实现了最基本的侧滑效果,相信很多小伙伴已经发现一个小问题了,修改Menu右侧的宽度时,我们需要修改我们的自定义方法,这样非常不方便,下面就为大家介绍一下如何通过自定义属性来控制这个的变化。代码主体同上,这里我就单独解释一下如何实现自定义属性。

  在Android的UI设计时我们往往不能满足于谷歌为我们提供的样式,这时就需要我们自定义样式,那么自定义样式的基本步骤是什么呢?1、书写xml文件;2、在布局文件中进行使用,特别注意xmlnx;3、在构造方法中获得我们设置的值。

  下面我们本篇的例子就按上面的步骤为大家进行解释:

  xml文件(在values文件下新建一个attr.xml):

<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="rightPadding" format="dimension"></attr> <declare-styleable name="SlidingMenu">
<attr name="rightPadding"></attr>
</declare-styleable>
</resources>

  布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:hyman="http://schemas.android.com/apk/res/com.example.android_qq_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <com.example.menu.SlidingMenu
android:layout_width="match_parent"
android:layout_height="match_parent"
hyman:rightPadding="100dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
> <include layout="@layout/left_menu"/> <LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/qq"
/> </LinearLayout>
</com.example.menu.SlidingMenu> </RelativeLayout>

  红色标注处为我们需要修改的位置,需要注意的时红色部分中的蓝色部分一定要一致,蓝色后面的红色部分我们的项目包名,通过AndroidManifest.xml可以查找到。

  自定义类的构造方法中获得我们设置值:

  public SlidingMenu(Context context) {
this(context, null);
} /**
* 未使用自定义属性时调用此方法
* @param context
* @param attrs
*/
public SlidingMenu(Context context, AttributeSet attrs) {
this(context, attrs, 0);
} /**
* 当使用了自定义的样式时调用
* @param context
* @param attrs
* @param defStyle
*/
public SlidingMenu(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle); //获取我们定义的属性
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SlidingMenu, defStyle, 0);
int n = a.getIndexCount();//获得设置的自定义属性个数
for(int i=0; i<n; i++){
int attr = a.getIndex(i);
switch (attr) {
case R.styleable.SlidingMenu_rightPadding:
mMenuRightPadding = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, context.getResources().getDisplayMetrics()));
break;
}
}
a.recycle(); WindowManager wm = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics );
mScreenWidth = outMetrics.widthPixels; }

  代码我仅仅将三个构造方法公布于此,其他方法同上,大家可以结合查看。

  最终的效果:

  QQ左侧滑动显示之自定义属性