你的位置:首页 > 操作系统

[操作系统]DrawerLayout使用


1 :DrawerLayout侧边栏用于实现如图所示的效果:

 

              

 

3:Activity代码如下,通过点击item跟换了Fragment。Fragment与Activity之间传递参数可通过SetArgument(New Bundle)实现,在Bundle中绑定数据;

 1 package cativity.cyq.drawerlayoutlearn; 2  3 import android.support.v4.app.ActionBarDrawerToggle; 4 import android.support.v4.widget.DrawerLayout; 5 import android.support.v7.app.ActionBarActivity; 6 import android.os.Bundle; 7 import android.view.View; 8 import android.widget.AdapterView; 9 import android.widget.ArrayAdapter;10 import android.widget.ListView;11 import android.widget.Toast;12 13 import java.util.ArrayList;14 15 import static android.widget.Toast.LENGTH_SHORT;16 17 18 public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {19 20   private DrawerLayout drawerLayout;21   private ListView menuListview;22   private ArrayList<String> menuData;23   private ArrayAdapter<String> menuAdapter;24   private ActionBarDrawerToggle mDrawerToggle;25 26   @Override27   protected void onCreate(Bundle savedInstanceState) {28     super.onCreate(savedInstanceState);29     setContentView(R.layout.activity_main);30 31     drawerLayout = (DrawerLayout) findViewById(R.id.root_drawerlayout);32     menuListview = (ListView) findViewById(R.id.left_drawerlayout);33     menuData = new ArrayList<>();34     for (int i = 0; i < 7; i++)35       menuData.add("菜单项" + i);36     menuAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, menuData);37     menuListview.setAdapter(menuAdapter);38 39     menuListview.setOnItemClickListener(this);40 41     //监听DrawerLayout的打开和关闭事件42     mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.menubar, R.string.drawerOpen, R.string.drawerClose) {43       @Override44       public void onDrawerOpened(View drawerView) {45         super.onDrawerOpened(drawerView);46         Toast.makeText(getApplication(), "打开", LENGTH_SHORT).show();47       }48 49       @Override50       public void onDrawerClosed(View drawerView) {51         super.onDrawerClosed(drawerView);52         Toast.makeText(getApplication(), "关闭", Toast.LENGTH_SHORT).show();53       }54     };55     drawerLayout.setDrawerListener(mDrawerToggle);56 57   }58 59   /* 为DrawerLayout的元素设置监听事件 */60   @Override61   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {62     Toast.makeText(this, "你选择的是:" + position, LENGTH_SHORT).show();63     MyFragment contentFragment = new MyFragment();64    /*通过setArgument(new Bundle())在Fragment的控制器和视图之间传递参数*/65     Bundle args = new Bundle();66     args.putString("fragmentdata", menuData.get(position));67     contentFragment.setArguments(args);68 69     getFragmentManager().beginTransaction().replace(R.id.main_contant, contentFragment).commit();70 71     drawerLayout.closeDrawer(menuListview);72   }73 74 75 }