1. 程式人生 > >android DrawerLayout 側邊欄實現

android DrawerLayout 側邊欄實現

現在實現側邊欄比較簡單了,官方提供的DrawerLayout可以很方便實現。
主要實現方法是:用DrawerLayout 作為介面根控制元件。在DrawerLayout裡面第一個View為當前介面主內容;第二個和第三個View為抽屜選單內容。如果當前介面只需要一個抽屜選單,則第三個View可以省略。
第一個View的寬高應當設定為match_parent
第二、三個View需要設定android:layout_gravity=”left”,和android:layout_gravity=”right”且一搬高度設定為match_parent,寬度為固定值,即側滑選單的寬度,寬度應該不超過320dp,這樣使用者可以在選單開啟的時候看到部分內容介面。如果需要監聽選單開啟關閉事件,則需要呼叫 DrawerLayout類的setDrawerListener()
該介面提供了選單開啟關閉等事件的回撥函式,例如
onDrawerOpened()

onDrawerClosed()
效果圖:
這裡寫圖片描述


描述一下:右側滑出側邊欄,包括一個標題,一個車輛列表,點選列表,右側滑出一個與側邊欄等寬的popupwindow,也包括標題與列表,點選popupwindow消失。主要有兩點,第一是側邊欄,第二是popupwindow以及滑動動畫
上程式碼:
主佈局activity_favorite_car.xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/id_drawerLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#f2f2f2">
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"
>
<boerpower.com.boerchargingpile.UI.CustomTitles.TitleLayout android:id="@+id/id_titleLayot" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@mipmap/top"> </boerpower.com.boerchargingpile.UI.CustomTitles.TitleLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp" android:layout_marginTop="10dp" android:background="#ffffff" android:orientation="vertical"> <ImageView android:id="@+id/id_imageMyCar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="88dp" android:layout_marginBottom="88dp" android:src="@mipmap/mycar_2" /> </LinearLayout> <LinearLayout android:id="@+id/id_linearCarKind" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:background="@drawable/rect_white" android:padding="10dp" android:gravity="center"> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:textSize="14sp" android:layout_weight="1" android:text="@string/mycar_kind" android:drawableLeft="@mipmap/mycar" android:drawablePadding="10dp" android:textColor="#3a3a3a"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/next_arrow" /> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/id_right_menu" android:layout_width="240dp" android:layout_height="match_parent" android:layout_gravity="right" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:background="@mipmap/top" android:orientation="horizontal"> <ImageView android:id="@+id/id_imageUp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/back" android:layout_margin="12dp"/> <TextView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" android:text="@string/mycar_favorite" android:textColor="#ffffff" android:textSize="17sp" /> </LinearLayout> <ListView android:id="@+id/id_listView" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff" android:cacheColorHint="#00000000" android:divider="#f2f2f2" android:dividerHeight="1dp"/> </LinearLayout> </android.support.v4.widget.DrawerLayout>

主介面程式碼

//我的愛車
public class FavoriteCarActivity extends BaseActivity implements TitleLayout.titleLayoutClick {
    private TitleLayout titleLayout;
    private ImageView imageViewCar;
    private LinearLayout linearLayoutCarKind;
    private LinearLayout linearLayoutRight;//右邊欄
    private DrawerLayout mDrawerLayout;
    private ListView listViewCar;//車名稱
    private ArrayList<String> carNameList = new ArrayList<>();//車名稱
    private ArrayList<String> carModelList = new ArrayList<>();//車型別
    private PopupWindow popupWindow = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite_car);
        titleLayout = (TitleLayout) findViewById(R.id.id_titleLayot);
        titleLayout.setTitle("我的愛車");
        imageViewCar = (ImageView) findViewById(R.id.id_imageMyCar);
        ImageView imageViewUp = (ImageView) findViewById(R.id.id_imageUp);
        linearLayoutCarKind = (LinearLayout) findViewById(R.id.id_linearCarKind);
        linearLayoutRight = (LinearLayout) findViewById(R.id.id_right_menu);
        linearLayoutCarKind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OpenRightMenu();
            }
        });
        mDrawerLayout = (DrawerLayout) findViewById(R.id.id_drawerLayout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED,
                Gravity.RIGHT);
        listViewCar = (ListView) findViewById(R.id.id_listView);
        for (int i = 0; i < 10; i++) {
            carNameList.add("保時捷");
            carModelList.add("Panamera");
        }

        CarAdapter carAdapter = new CarAdapter();
        listViewCar.setAdapter(carAdapter);
        listViewCar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                showCarModelPopupWindow();
            }
        });
        imageViewUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDrawerLayout.closeDrawers();
            }
        });
    }


    public void OpenRightMenu() {
        mDrawerLayout.openDrawer(Gravity.RIGHT);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED,
                Gravity.RIGHT);
    }

    private class CarAdapter extends BaseAdapter {

        public CarAdapter() {

        }

        @Override
        public int getCount() {
            return carNameList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(FavoriteCarActivity.this).inflate(R.layout.car_name_item, null);
            }

            TextView textViewCarName = ViewHolder.get(convertView, R.id.id_textViewCar);
            textViewCarName.setText(carNameList.get(position));


            return convertView;
        }

    }

    @Override
    public void leftViewClick() {
        finish();
    }

    @Override
    public void rightViewClick() {

    }


    private void showCarModelPopupWindow() {
        View view = View.inflate(FavoriteCarActivity.this, R.layout.car_model_list, null);
        ImageView imageViewUp = (ImageView) view.findViewById(R.id.id_imageUp);
        TextView textViewTitle = (TextView) view.findViewById(R.id.id_textViewCarName);
        ListView listViewCarModel = (ListView) view.findViewById(R.id.id_listViewCarModel);
        popupWindow = new PopupWindow(view, linearLayoutRight.getWidth(),
                LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setAnimationStyle(R.style.MenuAnimationLeftRight);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());//需要設定背景,用物理鍵返回的時候
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);  //設定點選螢幕其它地方彈出框消失
        CarModelAdapter carModelAdapter = new CarModelAdapter();
        listViewCarModel.setAdapter(carModelAdapter);
        listViewCarModel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                popupWindow.dismiss();
            }
        });
        popupWindow.showAtLocation(titleLayout, Gravity.RIGHT, 0, 0);
        imageViewUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    private class CarModelAdapter extends BaseAdapter {

        public CarModelAdapter() {

        }

        @Override
        public int getCount() {
            return carModelList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(FavoriteCarActivity.this).inflate(R.layout.car_model_item, null);
            }

            TextView textViewCarName = ViewHolder.get(convertView, R.id.id_textViewCarModel);
            textViewCarName.setText(carModelList.get(position));


            return convertView;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                mDrawerLayout.closeDrawers();
            } else {
                return super.onKeyDown(keyCode, event);
            }


            return true;
        }


        return super.onKeyDown(keyCode, event);
    }
}

標題類TitleLayout.java

/**
 * Created by dell on 2015/11/10.
 * 佈局標題
 */
public class TitleLayout extends RelativeLayout {
    TextView textViewContent;
    LinearLayout linearLeft;
    ImageView imageViewLeft;
    LinearLayout linearRight;
    ImageView imageViewRight;
    TextView textViewRight;
    private titleLayoutClick mListener;

    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this);
        textViewContent = (TextView) findViewById(R.id.id_textviewContent);
        linearLeft = (LinearLayout) findViewById(R.id.id_linearLeft);
        imageViewLeft = (ImageView)findViewById(R.id.id_left);
        linearRight = (LinearLayout) findViewById(R.id.id_linearRight);
        imageViewRight = (ImageView)findViewById(R.id.id_right);
        textViewRight = (TextView) findViewById(R.id.id_rightText);
        try{
            mListener = (titleLayoutClick) context;
        }catch (Exception e){
            e.printStackTrace();
        }

        linearLeft.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.leftViewClick();
                }
            }
        });
        linearRight.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.rightViewClick();
                }

            }
        });

    }

    public void setTitle(String title) {
        textViewContent.setText(title);
    }

    //設定右邊圖片
    public void setLinearRightImage(int drawableID) {
        imageViewRight.setBackgroundResource(drawableID);
    }
    //設定左邊圖片
    public void setLinearLeftImage(int drawableID) {
        imageViewLeft.setBackgroundResource(drawableID);
    }

    //設定右邊文字
    public void setLinearRightText(String rightTextString) {
        textViewRight.setText(rightTextString);
    }

    //設定右邊圖片為可見,根據viewID判斷文字與圖片的顯示,0顯示圖片,1顯示文字
    public void setLinearRightVisibility(int viewID) {

        linearRight.setVisibility(View.VISIBLE);
        if(viewID==0){
            imageViewRight.setVisibility(View.VISIBLE);
            textViewRight.setVisibility(View.INVISIBLE);
        }else if(viewID==1){
            textViewRight.setVisibility(View.VISIBLE);
            imageViewRight.setVisibility(View.INVISIBLE);
        }
    }

    public interface titleLayoutClick {
        public void leftViewClick();//左圖片點選
        public void rightViewClick();//右邊圖片點選
    }
}

標題類佈局title.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/id_top"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/id_linearLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true">

        <ImageView
            android:id="@+id/id_left"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="12dp"
            android:background="@mipmap/back" />

    </LinearLayout>

    <LinearLayout

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

        <TextView
            android:id="@+id/id_textviewContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="12dp"
            android:textColor="@color/white"
            android:textSize="17sp"/>

    </LinearLayout>


    <LinearLayout
        android:id="@+id/id_linearRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:visibility="invisible">

        <ImageView
            android:id="@+id/id_right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="12dp" />
        <TextView
            android:id="@+id/id_rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="12dp"
            android:textSize="14sp"
            android:textColor="#ffffff"/>
    </LinearLayout>
</RelativeLayout>

列表項佈局就不寫了
動畫style

 <!-- PopupWindow左右滑動的視窗動畫 -->
    <style name="MenuAnimationLeftRight">
        <item name="android:windowEnterAnimation">@anim/menu_fadein_right</item>
        <item name="android:windowExitAnimation">@anim/menu_fadein_left</item>
    </style>

menu_fadein_right

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="500"
        android:fromXDelta="100%"
        android:toXDelta="0"
        />
</set>

menu_fadein_left

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="500"
        android:fromXDelta="0"
        android:toXDelta="100%" />
</set>