左邊側滑與標題欄圖示互動
Xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer"
xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:app=“http://schemas.android.com/apk/res-auto”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fragment"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>
Activity:
package com.example.work9_10;
import android.support.design.widget.TabLayout;
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.os.Bundle;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
//定義變數
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取資源ID drawer=findViewById(R.id.drawer); //新增側滑佈局 if (savedInstanceState==null){ getSupportFragmentManager().beginTransaction() //側滑的id;要為側滑新增的佈局 .add(R.id.fragment,new leftFragment()) .commit(); } initData(); } private void initData() { //允許標題欄展示左邊圖示 getSupportActionBar().setDisplayHomeAsUpEnabled(true); //圖示toogle和側滑聯絡 toggle=new ActionBarDrawerToggle(this,drawer,R.string.open_drawer,R.string.close_drawer); drawer.addDrawerListener(toggle); toggle.syncState(); } //點選圖示,開啟或關閉側滑 public boolean onOptionsItemSelected(MenuItem item){ if (toggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); }
}
為側滑新增的佈局(只對佈局加了背景):
package com.example.work9_10;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class leftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.leftfragment,container,false);
return view;
}
}