Android--側滑選單
阿新 • • 發佈:2018-12-03
效果:
---向右滑動-->
實現:
自定義view:
public class LeftMenuView extends HorizontalScrollView { /**定義橫向滾動條佈局*/ private LinearLayout mScrollView; /**定義選單區域*/ private ViewGroup mMenu; /**定義主顯示區域*/ private ViewGroup mContent; /**定義螢幕寬度*/ private int mScreenWidth; /**定義選單右邊距為50dp*/private int mMenuRightPadding = 50; /**定義只設置一次自己和子檢視的寬和高*/ private boolean call; /**定義選單寬度*/ private int mMenuWidth; /** * 構造方法 * 初始化資料 * */ public LeftMenuView(Context context, AttributeSet attrs) { super(context, attrs); //獲取視窗管理器服務 WindowManager wm= (WindowManager) context.getSystemService(context.WINDOW_SERVICE); //建立顯示尺寸物件 DisplayMetrics dm=new DisplayMetrics(); //獲取當前螢幕的寬高尺寸 wm.getDefaultDisplay().getMetrics(dm); //為螢幕寬度賦值 mScreenWidth=dm.widthPixels; //將50dp邊距轉為畫素值px mMenuRightPadding= (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,50, context.getResources().getDisplayMetrics()); //隱藏滾動條 this.setHorizontalScrollBarEnabled(false); } /** * 設定滾動檢視與子檢視的寬和高 * */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //用於判斷只設置一次尺寸 if (!call){ //獲取滾動檢視中的子佈局 mScrollView = (LinearLayout) getChildAt(0); //獲取選單區域 mMenu = (ViewGroup) mScrollView.getChildAt(0); //獲取主顯示區域 mContent = (ViewGroup) mScrollView.getChildAt(1); //設定選單寬度 mMenuWidth = mMenu.getLayoutParams().width = mScreenWidth - mMenuRightPadding; //設定主顯示區域寬度 mContent.getLayoutParams().width = mScreenWidth; call = true; } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } /** * 設定偏移量讓選單隱藏 * */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (changed) { //滾動條向右移動,主顯示區域向左移動 this.scrollTo(mMenuWidth, 0); } } }
main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--自定義橫向滾動條--> <com.example.shanshan.leftmenu.LeftMenuView android:layout_width="match_parent" android:layout_height="match_parent"> <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="@color/colorPrimaryDark"> </LinearLayout> </LinearLayout> </com.example.shanshan.leftmenu.LeftMenuView> </RelativeLayout>