Android 使用V4包寫側滑菜單(android.support.v4.widget.DrawerLayout)


  在Android 中寫側滑菜單可以自定義,也可以使用安卓官方自帶的v4包,也有第三方包可以用。這里記錄官方的

android.support.v4.widget.DrawerLayout

這種方法比較簡單,在xml布局文件中搭建好,在Activity中調用
m.openDrawer(Gravity.LEFT);方法就可以使用了。
注意點:這個方法不可以放在oncreat方法中直接使用,涉及線程的原因,這里不作介紹。
    界面內容都放在v4包內,如下
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
界面內容
</android.support.v4.widget.DrawerLayout>

界面布局在v4包內會有些快捷詞沒法聯想出來,所以最好先寫好界面,然后在頭尾加上v4包

側滑效果有兩種:手指側滑和點擊彈出側滑界面,先上效果圖:






XML文件布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/draw"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
<!--主界面-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#000000"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>
<!--側滑界面-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" android:layout_gravity="left"//這個屬性決定側滑界面是左側滑還是右側滑
            android:background="#ded3d3"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btn2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="#000000" />

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


</LinearLayout>

 






 
Maintivity.java文件
 
        
public class MainActivity extends AppCompatActivity {
    DrawerLayout drawerLayout;
    Button btn, btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerLayout = (DrawerLayout) findViewById(R.id.draw);
        btn = (Button) findViewById(R.id.btn);
        btn2 = (Button) findViewById(R.id.btn2);
//實現方法一:
定義好xml文件后手指側滑就可以拉出側滑界面了
//實現方法二:
定義好xml文件后,在java文件中添加點擊事件也可以拉出側滑菜單,代碼如下:

// 點擊主界面中的按鈕彈出側滑界面 btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawerLayout.openDrawer(Gravity.LEFT); } }); // 點擊側滑界面中的按鈕縮回側滑界面 btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { drawerLayout.closeDrawer(Gravity.LEFT); } }); } }
 
        

 

注意:主界面布局一定要放在側滑界面的上面,否則側滑界面中無法添加點擊事件








免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM