天天看點

Android的GridView控件

GridView控件是可以用來顯示二維排列的控件,這裡在上一篇TabHost控件的基礎上添加了一個GridView控件,用作Tab頁的顯示内容。

效果圖:

Android的GridView控件

帖代碼:

public class OrderClientActivity extends Activity {
	TabHost tabHost;
	String[] dishType=new String[]{"1","2","3","4","5","6","7"};
	GridView gridView;
	
	String[] dishName=new String[]{"1","2","3","4","5","6","7","8","9","10","11","12"};
	String picPath=Environment.getExternalStorageDirectory().getPath() + "/picture/";
	
	GridViewAdapter gridViewAdapter;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.orderform);
        
        // 擷取TabHost對象
		TabHost tabHost = (TabHost) findViewById(R.id.tabhost);
		// 如果沒有繼承TabActivity時,通過該種方法加載啟動tabHost
		tabHost.setup();
        
		gridView=(GridView)findViewById(R.id.view1);
		gridViewAdapter=new GridViewAdapter(this);
		gridView.setAdapter(gridViewAdapter);
		
		for(int i=0;i<dishType.length;i++){
			TabHost.TabSpec tabSpec=tabHost.newTabSpec(dishType[i]);
			tabSpec.setIndicator(dishType[i],getResources().getDrawable(R.drawable.ic_launcher));
		    tabSpec.setContent(R.id.view1);
			tabHost.addTab(tabSpec);
		}
		
		tabHost.setCurrentTab(1);
		tabHost.setCurrentTab(0);
		
		new AsyncLoadImage().execute(100);
    }
    
    class AsyncLoadImage extends AsyncTask<Object, Bitmap, Object>{

		@Override
		protected Object doInBackground(Object... params) {
			Bitmap bitmap;
			
			Log.i("加載線程", "");
			
			// TODO Auto-generated method stub
			for(int i=0;i<dishName.length;i++){
				Log.i("圖檔路徑", picPath + dishName[i] + ".jpg");
				bitmap=BitmapFactory.decodeFile(picPath + dishName[i] + ".jpg");
				
				if(bitmap != null){
					publishProgress(bitmap);
					Log.i("圖檔解析", "正确");
				}
				else
					Log.i("圖檔解析", "錯誤");
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Bitmap... values) {
			// TODO Auto-generated method stub
			for(Bitmap b : values){
				gridViewAdapter.addPic(b);
				gridViewAdapter.notifyDataSetChanged();
			}
		}
 	
		
    }
    class GridViewAdapter extends BaseAdapter{

    	Context context;
    	private ArrayList<Bitmap> picList=new ArrayList<Bitmap>();
    	
    	GridViewAdapter(Context context){
    		this.context=context;
    	}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return picList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return picList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public void addPic(Bitmap bitmap){
			picList.add(bitmap);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Log.i("得到view", position + "");
			
			ImageView image = null;
			if(convertView == null){
				image=new ImageView(context);
				
			}
			else{
				image=(ImageView)convertView;
			}
			image.setLayoutParams(new GridView.LayoutParams((getWindowManager().getDefaultDisplay().getWidth()-3)/2,(int) (getWindowManager().getDefaultDisplay().getWidth()/2*0.6)));//設定ImageView對象布局 
            image.setAdjustViewBounds(true);//設定邊界對齊 
            image.setScaleType(ImageView.ScaleType.FIT_XY);//設定刻度的類型 
            image.setPadding(0, 0, 0, 0);//設定間距 
			image.setImageBitmap(picList.get(position));
			return image;
		}
    	
    }
}
           

GridView需要通過Adapter來加載需要顯示的内容,在這裡我們自定義了BaseAdapter,必須實作幾個方法,其中getCount()和getView()是必須實作的方法,getView()用來提供GridView顯示的每一個Item。關于Adapter的詳細情況可以參考  Android之Adapter用法總結。

另外,實際的運作過程中,發現Gridview的圖檔加載很卡,是以我們改成了異步加載圖檔,用到了AsyncTask類,這是Android提供的一個輕量級的線程既能在背景線程中執行一些耗時操作,又有方法直接更新ui,關于AsyncTask的詳細介紹可以參考:android AsyncTask介紹。

這裡如果沒有必要用到異步加載,可以在GridViewAdapter裡直接給picList指派。

布局檔案:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
	android:id="@+id/hometabs"
	android:orientation="vertical"
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent">
    <!-- TabHost必須包含一個 TabWidget和一個FrameLayout--> 
    <TabHost android:id="@+id/tabhost"
     	android:layout_width="fill_parent"
     	android:layout_height="wrap_content"
     	android:layout_weight="1">
     	<LinearLayout
			android:orientation="vertical"
			android:layout_width="fill_parent"
			android:layout_height="fill_parent">
			<HorizontalScrollView
			    android:layout_width="fill_parent"
			    android:layout_height="wrap_content"
			    android:scrollbars="none">
			    <!-- TabWidget的id屬性必須為 @android:id/tabs-->			
	     	  	<TabWidget android:id="@android:id/tabs" 
		      	android:orientation="horizontal"
		      	android:layout_width="fill_parent"
		      	android:layout_height="wrap_content">
	        	</TabWidget>
			</HorizontalScrollView>
			
	     	<!-- FrameLayout的id屬性必須為 @android:id/tabcontent-->
		     <FrameLayout 
		          android:id="@android:id/tabcontent"
			      android:layout_width="fill_parent"
			      android:layout_height="fill_parent">
			      
			      <GridView 
			          android:id="@+id/view1"
			          android:listSelector="#000000"
			          android:layout_width="fill_parent"
			          android:layout_height="wrap_content"
			          android:padding="0dip"
			          android:layout_margin="0dip"
			          android:numColumns="2"
			          android:horizontalSpacing="3dip"
			          android:verticalSpacing="3dip"
			          android:stretchMode="columnWidth"
			          android:gravity="fill"/>"
			    	
		     </FrameLayout>
	     
	     </LinearLayout>
    </TabHost>
    <LinearLayout 
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hha"/>
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hha2"/>
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hha3"/>
    </LinearLayout>
    
</LinearLayout>
           

在布局檔案裡看到,GridView設定了一個屬性android:listSelector,這個屬性用來設定GridView的每個item 的背景。如果沒有設定這個屬性,每個item在點選的時候都有一個藍色邊框,我們可以設定成我們想要的顔色,不想顯示的話可以直接設定成背景色。

下一篇介紹GridView的更複雜的用法。