Android studio DrawerLayout

网上开源项目地址:https://github.com/ikimuhendis/LDrawer

效果图:

build.gradle

compile 'com.ikimuhendis:ldrawer:0.1'

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ldrawer_color">#FFFFFF</color>
    <color name="actionbar_color">#bf360c</color>
    <color name="drawer_arrow_second_color">#303f9f</color>
</resources>

styles.xml

<resources>

    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/ActionBar</item>
    </style>

    <style name="ActionBar" parent="android:Widget.ActionBar">
        <item name="android:background">@color/actionbar_color</item>
        <item name="android:icon">@android:color/transparent</item>
        <item name="android:titleTextStyle">@style/ActionBar.TitleText</item>
    </style>

    <style name="ActionBar.TitleText" parent="android:TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">@android:color/white</item>
        <item name="android:textSize">18sp</item>
    </style>

</resources>

项目依赖开发包v4 : android.support.v4.app.ActionBarDrawerToggle,自定义 DrawerArrowDrawable,ActionBarDrawerToggle

import android.app.ActionBar;
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.lang.reflect.Method;

import ldrawer.lanyan.com.ldrawer.R;

public class ActionBarDrawerToggle extends android.support.v4.app.ActionBarDrawerToggle {

    private static final String TAG = ActionBarDrawerToggle.class.getName();

    protected Activity mActivity;
    protected DrawerLayout mDrawerLayout;

    protected int mOpenDrawerContentDescRes;
    protected int mCloseDrawerContentDescRes;
    protected DrawerArrowDrawable mDrawerImage;
    protected boolean animateEnabled;

    public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, int drawerImageRes, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
        super(activity, drawerLayout, drawerImageRes, openDrawerContentDescRes, closeDrawerContentDescRes);
    }

    public ActionBarDrawerToggle(Activity activity, DrawerLayout drawerLayout, DrawerArrowDrawable drawerImage, int openDrawerContentDescRes, int closeDrawerContentDescRes) {
        super(activity, drawerLayout, R.mipmap.ic_drawer, openDrawerContentDescRes, closeDrawerContentDescRes);
        mActivity = activity;
        mDrawerLayout = drawerLayout;
        mOpenDrawerContentDescRes = openDrawerContentDescRes;
        mCloseDrawerContentDescRes = closeDrawerContentDescRes;
        mDrawerImage = drawerImage;
        animateEnabled = true;
    }

    public void syncState() {
        if (mDrawerImage == null) {
            super.syncState();
            return;
        }
        if (animateEnabled) {
            if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
                mDrawerImage.setProgress(1.f);
            } else {
                mDrawerImage.setProgress(0.f);
            }
        }
        setActionBarUpIndicator();
        setActionBarDescription();
    }

    public void setDrawerIndicatorEnabled(boolean enable) {
        if (mDrawerImage == null) {
            super.setDrawerIndicatorEnabled(enable);
            return;
        }
        setActionBarUpIndicator();
        setActionBarDescription();
    }

    public boolean isDrawerIndicatorEnabled() {
        if (mDrawerImage == null) {
            return super.isDrawerIndicatorEnabled();
        }
        return true;
    }

    public void onConfigurationChanged(Configuration newConfig) {
        if (mDrawerImage == null) {
            super.onConfigurationChanged(newConfig);
            return;
        }
        syncState();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
        if (mDrawerImage == null) {
            super.onDrawerSlide(drawerView, slideOffset);
            return;
        }
        if (animateEnabled) {
            mDrawerImage.setVerticalMirror(!mDrawerLayout.isDrawerOpen(GravityCompat.START));
            mDrawerImage.setProgress(slideOffset);
        }
    }

    @Override
    public void onDrawerOpened(View drawerView) {
        if (mDrawerImage == null) {
            super.onDrawerOpened(drawerView);
            return;
        }
        if (animateEnabled) {
            mDrawerImage.setProgress(1.f);
        }
        setActionBarDescription();
    }

    @Override
    public void onDrawerClosed(View drawerView) {
        if (mDrawerImage == null) {
            super.onDrawerClosed(drawerView);
            return;
        }
        if (animateEnabled) {
            mDrawerImage.setProgress(0.f);
        }
        setActionBarDescription();
    }

    protected void setActionBarUpIndicator() {
        if (mActivity != null) {
            try {
                Method setHomeAsUpIndicator = ActionBar.class.getDeclaredMethod("setHomeAsUpIndicator",
                    Drawable.class);
                setHomeAsUpIndicator.invoke(mActivity.getActionBar(), mDrawerImage);
                return;
            } catch (Exception e) {
                Log.e(TAG, "setActionBarUpIndicator error", e);
            }

            final View home = mActivity.findViewById(android.R.id.home);
            if (home == null) {
                return;
            }

            final ViewGroup parent = (ViewGroup) home.getParent();
            final int childCount = parent.getChildCount();
            if (childCount != 2) {
                return;
            }

            final View first = parent.getChildAt(0);
            final View second = parent.getChildAt(1);
            final View up = first.getId() == android.R.id.home ? second : first;

            if (up instanceof ImageView) {
                ImageView upV = (ImageView) up;
                upV.setImageDrawable(mDrawerImage);
            }
        }
    }

    protected void setActionBarDescription() {
        if (mActivity != null && mActivity.getActionBar() != null) {
            try {
                Method setHomeActionContentDescription = ActionBar.class.getDeclaredMethod(
                    "setHomeActionContentDescription", Integer.TYPE);
                setHomeActionContentDescription.invoke(mActivity.getActionBar(),
                    mDrawerLayout.isDrawerOpen(GravityCompat.START) ? mOpenDrawerContentDescRes : mCloseDrawerContentDescRes);
                if (Build.VERSION.SDK_INT <= 19) {
                    mActivity.getActionBar().setSubtitle(mActivity.getActionBar().getSubtitle());
                }
            } catch (Exception e) {
                Log.e(TAG, "setActionBarUpIndicator", e);
            }
        }
    }

    public void setAnimateEnabled(boolean enabled) {
        this.animateEnabled = enabled;
    }

    public boolean isAnimateEnabled() {
        return this.animateEnabled;
    }

}
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;

import ldrawer.lanyan.com.ldrawer.R;

public abstract class DrawerArrowDrawable extends Drawable {
    private static final float ARROW_HEAD_ANGLE = (float) Math.toRadians(45.0D);
    protected float mBarGap;
    protected float mBarSize;
    protected float mBarThickness;
    protected float mMiddleArrowSize;
    protected final Paint mPaint = new Paint();
    protected final Path mPath = new Path();
    protected float mProgress;
    protected int mSize;
    protected float mVerticalMirror = 1f;
    protected float mTopBottomArrowSize;
    protected Context context;

    public DrawerArrowDrawable(Context context) {
        this.context = context;
        this.mPaint.setAntiAlias(true);
        this.mPaint.setColor(context.getResources().getColor(R.color.ldrawer_color));
        this.mSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_drawableSize);
        this.mBarSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_barSize);
        this.mTopBottomArrowSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_topBottomBarArrowSize);
        this.mBarThickness = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_thickness);
        this.mBarGap = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_gapBetweenBars);
        this.mMiddleArrowSize = context.getResources().getDimensionPixelSize(R.dimen.ldrawer_middleBarArrowSize);
        this.mPaint.setStyle(Paint.Style.STROKE);
        this.mPaint.setStrokeJoin(Paint.Join.ROUND);
        this.mPaint.setStrokeCap(Paint.Cap.SQUARE);
        this.mPaint.setStrokeWidth(this.mBarThickness);
    }

    protected float lerp(float paramFloat1, float paramFloat2, float paramFloat3) {
        return paramFloat1 + paramFloat3 * (paramFloat2 - paramFloat1);
    }

    public void draw(Canvas canvas) {
        Rect localRect = getBounds();
        float f1 = lerp(this.mBarSize, this.mTopBottomArrowSize, this.mProgress);
        float f2 = lerp(this.mBarSize, this.mMiddleArrowSize, this.mProgress);
        float f3 = lerp(0.0F, this.mBarThickness / 2.0F, this.mProgress);
        float f4 = lerp(0.0F, ARROW_HEAD_ANGLE, this.mProgress);
        float f5 = 0.0F;
        float f6 = 180.0F;
        float f7 = lerp(f5, f6, this.mProgress);
        float f8 = lerp(this.mBarGap + this.mBarThickness, 0.0F, this.mProgress);
        this.mPath.rewind();
        float f9 = -f2 / 2.0F;
        this.mPath.moveTo(f9 + f3, 0.0F);
        this.mPath.rLineTo(f2 - f3, 0.0F);
        float f10 = (float) Math.round(f1 * Math.cos(f4));
        float f11 = (float) Math.round(f1 * Math.sin(f4));
        this.mPath.moveTo(f9, f8);
        this.mPath.rLineTo(f10, f11);
        this.mPath.moveTo(f9, -f8);
        this.mPath.rLineTo(f10, -f11);
        this.mPath.moveTo(0.0F, 0.0F);
        this.mPath.close();
        canvas.save();
        if (!isLayoutRtl())
            canvas.rotate(180.0F, localRect.centerX(), localRect.centerY());
        canvas.rotate(f7 * mVerticalMirror, localRect.centerX(), localRect.centerY());
        canvas.translate(localRect.centerX(), localRect.centerY());
        canvas.drawPath(this.mPath, this.mPaint);
        canvas.restore();
    }

    public int getIntrinsicHeight() {
        return this.mSize;
    }

    public int getIntrinsicWidth() {
        return this.mSize;
    }

    public void setAlpha(int alpha) {
        this.mPaint.setAlpha(alpha);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.TRANSLUCENT;
    }

    public abstract boolean isLayoutRtl();

    public void setColorFilter(ColorFilter colorFilter) {
        this.mPaint.setColorFilter(colorFilter);
    }

    public void setVerticalMirror(boolean mVerticalMirror) {
        this.mVerticalMirror = mVerticalMirror ? 1 : -1;
    }

    public void setProgress(float paramFloat) {
        this.mProgress = paramFloat;
        invalidateSelf();
    }

    public void setColor(int resourceId) {
        this.mPaint.setColor(context.getResources().getColor(resourceId));
    }
}

测试代码:

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import com.ikimuhendis.ldrawer.ActionBarDrawerToggle;
import com.ikimuhendis.ldrawer.DrawerArrowDrawable;

public class SampleActivity extends Activity {

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private DrawerArrowDrawable drawerArrow;
    private boolean drawerArrowColor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);
        ActionBar ab = getActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setHomeButtonEnabled(true);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.navdrawer);

        drawerArrow = new DrawerArrowDrawable(this) {
            @Override
            public boolean isLayoutRtl() {
                return false;
            }
        };
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                drawerArrow, R.string.drawer_open,
                R.string.drawer_close) {

            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();

        String[] values = new String[]{
                "Stop Animation (Back icon)",
                "Stop Animation (Home icon)",
                "Start Animation",
                "Change Color",
                "GitHub Page",
                "Share",
                "Rate"
        };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, values);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position) {
                    case 0:
                        mDrawerToggle.setAnimateEnabled(false);
                        drawerArrow.setProgress(1f);
                        break;
                    case 1:
                        mDrawerToggle.setAnimateEnabled(false);
                        drawerArrow.setProgress(0f);
                        break;
                    case 2:
                        mDrawerToggle.setAnimateEnabled(true);
                        mDrawerToggle.syncState();
                        break;
                    case 3:
                        if (drawerArrowColor) {
                            drawerArrowColor = false;
                            drawerArrow.setColor(R.color.ldrawer_color);
                        } else {
                            drawerArrowColor = true;
                            drawerArrow.setColor(R.color.drawer_arrow_second_color);
                        }
                        mDrawerToggle.syncState();
                        break;
                    case 4:
                        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/IkiMuhendis/LDrawer"));
                        startActivity(browserIntent);
                        break;
                    case 5:
                        Intent share = new Intent(Intent.ACTION_SEND);
                        share.setType("text/plain");
                        share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        share.putExtra(Intent.EXTRA_SUBJECT,
                                getString(R.string.app_name));
                        share.putExtra(Intent.EXTRA_TEXT, getString(R.string.app_description) + "\n" +
                                "GitHub Page :  https://github.com/IkiMuhendis/LDrawer\n" +
                                "Sample App : https://play.google.com/store/apps/details?id=" +
                                getPackageName());
                        startActivity(Intent.createChooser(share,
                                getString(R.string.app_name)));
                        break;
                    case 6:
                        String appUrl = "https://play.google.com/store/apps/details?id=" + getPackageName();
                        Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(appUrl));
                        startActivity(rateIntent);
                        break;
                }

            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.closeDrawer(mDrawerList);
            } else {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}

布局文件:

<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/app_description"/>

    </RelativeLayout>

    <!-- The navigation drawer -->
    <ListView
        android:id="@+id/navdrawer"
        android:layout_width="@dimen/navdrawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:drawSelectorOnTop="false">
    </ListView>

</android.support.v4.widget.DrawerLayout>

注意:如果是自己导入已有项目,复制图片时可能复制到的文件夹不是drawable(而是 R.mipmap.ic_drawer),那么
R.drawable.ic_drawer会报错找不到R

时间: 2024-10-07 07:30:25

Android studio DrawerLayout的相关文章

Android Studio官方版DrawerLayout侧滑菜单解析

效果图如下 这是使用Android Studio新建的一个DrawerLayout项目跑出来后的效果(没有Android Studio的盆友赶紧去下载个吧). 生成后的代码有点混乱,稍微整理一下,那么先看布局文件 activity_main.xml: <?xml version="1.0" encoding="utf-8"?>   <android.support.v4.widget.DrawerLayout xmlns:android="

《Android Studio开发实战 从零基础到App上线》资源下载和内容勘误

http://blog.csdn.net/aqi00/article/details/72907534 http://blog.csdn.net/aqi00/article/details/73065392 版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] 资源下载 下面是<Android Studio开发实战 从零基础到App上线>一书用到的工具和代码资源:1.本书使用的Android Studio版本为2.2.3,因为Android官网现在不提供该版本的下载,所以博主

[Android] 升级了新的android studio之后 发生如下的报错,The following classes could not be instantiated:

The following classes could not be instantiated:- android.support.v4.widget.DrawerLayout (Open Class, Show Exception) Tip: Use View.isInEditMode() in your custom views to skip code or show sample data when shown in the IDE 我使用了NavigationDrawer这个模块去创建

Android Studio 安装及常见问题

今年放假比去年早了一些,就提前回来了.感觉挺爽,结果教研室电脑没有带回来,悲剧是导师让我维护一下以前的项目,只能屁颠屁颠的搞起呀.只能用自己的笔记本搭建android开发环境.由于前阶段听说Android Studio用着爽歪歪,于是尝试在超卡的笔记本上跑Android Studio.哇咔咔,费了九牛二虎之力终于将Android Studio玩转了.先上个图,快过年了,祝大家新年快乐! Android官网也开始推广Android Studio了,以前官网好像提供Eclipse和ADT打包下载,现

Android Studio 连接真机不识别

本人也是初学..写错的请大神多多批评指正! 不胜荣幸!! 强烈推荐使用真机测试..除非是最后关头要测试各个Android系统版本.. 本人遇到的连不上的原因有以下几种: 1  --   手机设置问题.开USB调试   方法:  手机设置 - 开发人员选项 - USB调试  - 勾选 2  --   数据线问题.  有的数据线只能用来充电,有的可以连接存储.识别方法很简单..插上机器有USB存储设备的提示的就可以用.另外数据线如果都露线皮了..就赶紧扔了.十块八块的总比你为这个破问题纠结一下午的好

修改Android Studio默认的API Level(SDK版本)

原文:修改Android Studio默认的API Level(SDK版本) Android Studio(2.1.2)新建工程的时候只会让你选择最低支持的SDK版本,默认的目标编译SDK版本会以系统当前SDK中最新SDK platform作为目标的API Level.但是很多时候我们并不需要最新的SDK版本,如何修改呢? 方法是:修改工程目录中的Gradle Scripts->build.gradle(Module:app)中的相关行,具体见下图: 当然也可以图形化操作,右键工程目录选择"

Android studio界面相关设置

Android studio界面相关设置 原文出自 http://www.cnblogs.com/justinzhang/p/4274839.html 用惯了emacs的操作方式,每当使用一款新的编辑器的时候,第一个想到的就是这个工具有没有emacs的快捷键,Android studio也是一样的. 1. Android studio设置emacs的方式如下,点击File->Settings 选择其中的keymap,在keymap中选择emacs,这样就成功的设置好了emacs的操作模式: 2.

安装android studio报错Failed to install Intel HAXM.

在安装android studio的过程中,安装到android的模拟器加速器(intel HAXM)这一步时,报错: HAXM是用来管理硬件加速的,估计是用了这个东西模拟器就能Eclipse的龟速吧. 解决: 原因:没有找到reg.exe; 给reg.exe配置环境变量. reg.exe一般是在C:\Windows\System32\目录下. 可以将路径C:\Windows\System32\reg.exe配置在PATH下, 也可以直接将%SystemRoot%\system32;%Syste

Android Studio 初体验,从Eclipse到AS

这些天一直在忙着面试方面的准备以及不断更新完善我的Memory软件,不知不觉过去了好久. 由于我想对软件加入一些material design的新元素,因此去网上找对应的示例源码,突然发现除了各种教程上还在使用eclipse,这个世界几乎所有新的东东都被AndroidStudio包揽了,瞬间感觉不学AS简直就是不可逾越的交流鸿沟.因此网上买了个VPN翻墙,用了几天时间,终于搞明白了AS的基本用法.在此分享一下自己的学习心得. 自己是从Eclipse转到AS上的,所以在学习AS当中, 必然下意识的