当前位置:   article > 正文

DrawerLayout 的详细使用_drawerlayout设置使用详情

drawerlayout设置使用详情

直接上代码

package com.example.hexl.drawerlayout;


import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, View.OnClickListener, OnIndexSelectListener {
    private DrawerLayout mDrawerLayout;
    private ListView mListView;
    private ArrayList<String> datas;
    private ArrayAdapter<String> mAdapter;
    private ActionBarDrawerToggle mDrawerToggle;
    private String mtitle;
    private Toolbar mToolbar;
    private TextView mTv;
    private RelativeLayout relativeLayout;
    /*自定义 IndexView*/
    private IndexView view;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTv = (TextView) findViewById(R.id.beijing);
        relativeLayout = (RelativeLayout) findViewById(R.id.relative_layout);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.draw_layout);
        mListView = (ListView) findViewById(R.id.list_view);
        view = (IndexView) findViewById(R.id.index_view);
        view.setListener(this);

        mTv.setOnClickListener(this);
        /*获取头信息*/
        mtitle = (String) getTitle();

        /*初始化数据*/
        initData();

        mAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item, datas);

        mListView.setAdapter(mAdapter);
        /*增加点击事件替换 Fragment*/

        mListView.setOnItemClickListener(MainActivity.this);

//        mToolbar.setVisibility(View.GONE);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar,
                R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle("请选择省份");
                invalidateOptionsMenu(); /* 当执行此方法的时候系统会自动调用 onPrepareOptionsMenu()这个方法*/
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                getSupportActionBar().setTitle(mtitle);
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        /*开启 ActionBar 上的 ICON 功能*/
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private void initData() {
        datas = new ArrayList<>();
        datas.add("全部");
        datas.add("原创");
        datas.add("实拍");
        datas.add("试车");
        datas.add("花边");
        datas.add("事件");
        datas.add("新车");
        datas.add("广告");
        datas.add("技术");
        datas.add("二手车");
        datas.add("全部");
        datas.add("原创");
        datas.add("实拍");
        datas.add("试车");
        datas.add("花边");
        datas.add("事件");
        datas.add("新车");
        datas.add("广告");
        datas.add("技术");
        datas.add("二手车");
        datas.add("全部");
        datas.add("原创");
        datas.add("实拍");
        datas.add("试车");
        datas.add("花边");
        datas.add("事件");
        datas.add("新车");
        datas.add("广告");
        datas.add("技术");
        datas.add("二手车");
    }

    /**
     * 当点击北京的时候弹出 DrawerLayout
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.beijing:
                mDrawerLayout.openDrawer(Gravity.END);
                break;
        }
    }

    /**
     * @param menu menu
     * @return menu 布局
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 根据DrawerLayout的显示或隐藏来判断 menu 是否显示或隐藏
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean isDrawerOpen = mDrawerLayout.isDrawerOpen(relativeLayout);
        menu.findItem(R.id.action_websearch).setVisible(!isDrawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * @param item 根据传入的 id 跳转 webView
     * @return webView
     */

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_websearch:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                Uri uri = Uri.parse("http://www.baidu.com");
                intent.setData(uri);
                startActivity(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Fragment fragment = new FragmentContent();
        Bundle args = new Bundle();
        args.putString("args", datas.get(position));//把值传到 Fragment 中
        fragment.setArguments(args);
        FragmentManager manager = getFragmentManager();
        manager.beginTransaction().replace(R.id.frame_layout, fragment).commit();
        mDrawerLayout.closeDrawer(relativeLayout);
    }

    @Override
    public void onItemSelect(int position, String value) {
        Log.d("MainActivity", "position:" + position);
        Log.d("MainActivity", value);
        mListView.smoothScrollToPosition(position);
    }

}
package com.example.hexl.drawerlayout;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

/**
 * Created by hexl on 16/5/28.
 * 索引字母
 */
public class IndexView extends View {
    /*绘制索引字母的画笔*/
    private Paint mPaint;

    /*索引字母*/
    private String mIndex[] = {"↑", "☆", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"};
    /*获取 View 的高度,平均分索引字母*/
    private int mViewHeight, mViewWidth;
    /*字体大小*/
    private float mTextSize;
    /*判断是否已经被触摸*/
    private boolean mTouched = false;
    /*测量字体的大小*/
    private Rect mTextBound;

    /*回调选择的索引*/
    private OnIndexSelectListener listener;

    /*窗口、浮动 View 的容器,比 Acitivity 的显示更高一层*/
    private WindowManager mWindowManager;
    /*用于显示浮动的字体,类似 Toast*/
    private View mFloatView;
    /*悬浮 View 的宽度、*/
    private int mOverLyWidth;
    /*悬浮 View 的高度、*/
    private int mOverLyHeight;

    public IndexView(Context context) {
        this(context, null);
    }

    public IndexView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IndexView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initView();
    }

    /*做些初始化工作*/
    private void initView() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextBound = new Rect();

        /*设置浮动选中的索引*/
        /*获取 windowMan*/
        mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        /*overly 视图,通过 LayoutInflater 获取*/
        mFloatView = LayoutInflater.from(getContext()).inflate(R.layout.overlay_indexview, null);
        /*开启让其隐藏*/
        mFloatView.setVisibility(INVISIBLE);
        /*转换高度和宽度为 Sp*/
        mOverLyWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getResources().getDisplayMetrics());
        mOverLyHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getResources().getDisplayMetrics());
        post(new Runnable() {/*开线程*/
            @Override
            public void run() {
                WindowManager.LayoutParams layoutParams =
                        new WindowManager.LayoutParams(mOverLyWidth, mOverLyHeight,
                                WindowManager.LayoutParams.TYPE_APPLICATION,
                                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                                PixelFormat.TRANSLUCENT);
                mWindowManager.addView(mFloatView, layoutParams);
            }
        });
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mTouched) {
            canvas.drawColor(Color.RED);
        }
        for (int i = 0; i < mIndex.length; i++) {
            mPaint.setColor(Color.BLUE);//设置字体颜色
            mPaint.setTextSize(30.0f);//设置字体大小
//            mPaint.setTypeface(Typeface.DEFAULT);//设置字体风格
            /*
            * 字符串来衡量并返回它的界限
            * 索引的第一个字符的字符串来衡量
            * 最后一个字符字符串
            * 返回联合边界的所有文本。必须分配给调用者。
            * 由调用者返回在边界(分配)的最小矩形包含所有的字符,以隐含原点(0,0)。
            * */
            Log.d("IndexView", "----" + mIndex[i]);
            Log.d("IndexView", "mIndex[i].length():" + mIndex[i].length());
            Log.d("IndexView", "mTextBound:" + mTextBound);
            mPaint.getTextBounds(mIndex[i], 0, mIndex[i].length(), mTextBound);//不懂

            float formX = mViewWidth / 2.0f - mTextBound.width() / 2.0f;
            float formY = mTextSize * i + mTextSize / 2.0f + mTextBound.height() / 2.0f;
            canvas.drawText(mIndex[i], formX, formY, mPaint);
            mPaint.reset();
        }

    }

    /**
     * @param widthMeasureSpec  测量的宽度
     * @param heightMeasureSpec 测量的高度
     *                          必须调用setMeasuredDimension()这个方法否则会抛出非法状态异常 API 解释
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    /**
     * @param widthMeasureSpec 传入父 View 的测量标准
     * @return 测量的宽度
     *         测量本身大小,这里只测量宽度
     */
    private int measureWidth(int widthMeasureSpec) {
        /*定义 view 的宽度*/
        int width;
        /*获取当前 View 的测量模式*/
        int mode = MeasureSpec.getMode(widthMeasureSpec);
        /*
        * 获取当前 View的测量值,哲理得到的知识初步的值
        * 我们还需根据测量模式来确定我们期望的大小
        * */
        int size = MeasureSpec.getSize(widthMeasureSpec);
        /*
        * 如果,模式为精确模式
        * 当前 View 的宽度就是我们的 size
        * */
        if (mode == MeasureSpec.EXACTLY) {
            width = size;
        } else {
            /*否则的话我们就需要结合 padding 的值来确定*/
            int desire = size + getPaddingLeft() + getPaddingRight();
            if (mode == MeasureSpec.AT_MOST) {
                width = Math.min(desire, size);
            } else {
                width = desire;
            }
        }
        mViewWidth = width;
        return mViewWidth;
    }

    /**
     * 测量本身的高度
     *
     * @param heightMeasureSpec
     * @return 高度
     */
    private int measureHeight(int heightMeasureSpec) {
        int height;
        int mode = MeasureSpec.getMode(heightMeasureSpec);
        int size = MeasureSpec.getSize(heightMeasureSpec);
        if (mode == MeasureSpec.EXACTLY) {
            height = size;
        } else {
            int desire = size + getPaddingTop() + getPaddingBottom();
            if (mode == MeasureSpec.AT_MOST) {
                height = Math.min(desire, size);
            } else {
                height = desire;
            }
        }
        mViewHeight = height;
        mTextSize = mViewHeight * 1.0f / mIndex.length;
        return mViewHeight;
    }

    /**
     * @param event The touch screen event being processed.
     * @return true if you have consumed the event, false if you haven't. The default implementation always returns false.
     *         如果有触摸返回 true 否则返回 false
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float y = event.getY();
        int index = (int) (y / mTextSize);
        if (index >= 0 && index < mIndex.length) {
            selectItem(index);
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            mTouched = true;
        } else {
            mFloatView.setVisibility(INVISIBLE);
            mTouched = false;
        }
        invalidate();
        /*过滤其他触摸事件*/
        return true;
    }

    private void selectItem(int position) {
        mFloatView.setVisibility(VISIBLE);
        /*通过点击的位置获取每一个字母*/
        ((TextView) mFloatView).setText(mIndex[position]);
        Log.d("IndexView====    ", mIndex[position]);

        if (listener != null) {
            listener.onItemSelect(position, mIndex[position]);
        }
    }

    public void setListener(OnIndexSelectListener listener) {
        this.listener = listener;
    }


}
package com.example.hexl.drawerlayout;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by hexl on 16/5/28.
 * 内容
 */
public class FragmentContent extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_content,container,false);
        TextView tvContent = (TextView) view.findViewById(R.id.content_tv);
        tvContent.setText(getArguments().getString("args"));
        return view;
    }
}
package com.example.hexl.drawerlayout;

/*定义一个回调接口*/
public interface OnIndexSelectListener {
    /*返回选中的位置和对应的索引名*/
    void onItemSelect(int position, String value);
//    void onItemSelect(int postion);
}
下面是布局文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/draw_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/beijing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="北京" />

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

    <RelativeLayout
        android:id="@+id/relative_layout"
        android:layout_width="140dp"
        android:layout_height="match_parent"
        android:layout_gravity="end">

        <ListView
            android:id="@+id/list_view"
            android:layout_width="140dp"
            android:layout_height="match_parent"
            android:background="@android:color/holo_blue_light"
            android:choiceMode="singleChoice" />

        <com.example.hexl.drawerlayout.IndexView
            android:id="@+id/index_view"
            android:layout_width="10dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true" />
    </RelativeLayout>

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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/content_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="20sp" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/overly_text"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:text="A"
    android:gravity="center"
    android:background="#88000000"
    android:textSize="40sp"
    android:textColor="#ffffffff"
    android:layout_gravity="center">

</TextView>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/279650
推荐阅读
相关标签
  

闽ICP备14008679号