2010年2月24日 星期三

Android學習筆記 - 網格視圖(GridView)

1. 利用網格視圖(GridView)物件來呈現項目列表

2. MainActivity.java
package org.me.android_gridview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private GridView gridView;
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        gridView = (GridView) findViewById(R.id.gridView);
        final String[] list = new String[]{"王建民","郭泓志","倪福德","胡金龍"};
        //設定列表內容
        ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
        //設定列數
        gridView.setNumColumns(2);
        gridView.setAdapter(adapter);
        //項目被點選時,回應的動作
        gridView.setOnItemClickListener(new GridView.OnItemClickListener(){
           @Override
           public void onItemClick(AdapterView adapterView,View view,int position,long id) {
               Toast.makeText(MainActivity.this, "您選擇的是"+list[position], Toast.LENGTH_SHORT).show();
           }
        });
    }
}


3. main.xml(Layout)
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">" 
    <GridView
        android:id="@+id/gridView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </GridView>
</LinearLayout>


4. 執行之後的畫面。

沒有留言:

張貼留言