抽屉样式作为一种比较常用的View,有很多实现方式。
这里是一种简单的实现方式:
第一步:布局文件
<!-- android:content 要展开的layout content android:handle 委托要展开的图片 --> <SlidingDrawer android:id="@+id/sliding" android:layout_width="match_parent" android:layout_height="match_parent" android:content="@+id/allApps" android:handle="@+id/imageViewIcon" android:orientation="vertical" > <GridView android:id="@+id/allApps" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/ic_launcher" android:columnWidth="60dp" android:gravity="center" android:horizontalSpacing="10dp" android:numColumns="auto_fit" android:padding="10dp" android:stretchMode="columnWidth" android:verticalSpacing="10dp" /> <ImageView android:id="@+id/imageViewIcon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> </SlidingDrawer>
第二部:MainActivity
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = new Intent(Intent.ACTION_MAIN, null); intent.addCategory(Intent.CATEGORY_LAUNCHER); apps = getPackageManager().queryIntentActivities(intent, 0); gv = (GridView) findViewById(R.id.allApps); sd = (SlidingDrawer) findViewById(R.id.sliding); iv = (ImageView) findViewById(R.id.imageViewIcon); gv.setAdapter(new GridAdapter()); sd.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener(){// 开抽屉 @Override public void onDrawerOpened() { iv.setImageResource(R.drawable.ic_launcher); } }); sd.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() { @Override public void onDrawerClosed() { iv.setImageResource(R.drawable.ic_launcher);// 响应关抽屉事件 } }); } //适配器 public class GridAdapter extends BaseAdapter { public GridAdapter() { } public int getCount() { // TODO Auto-generated method stub return apps.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return apps.get(position); } public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ImageView imageView = null; if (convertView == null) { imageView = new ImageView(MainActivity.this); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); imageView.setLayoutParams(new GridView.LayoutParams(50, 50)); } else { imageView = (ImageView) convertView; } ResolveInfo ri = apps.get(position); imageView.setImageDrawable(ri.activityInfo.loadIcon(getPackageManager())); return imageView; } }