Gallery是一個鎖定中心條目的控件 可以點擊響應事件 擁有水平滾動的列表視圖 一般用於瀏覽圖片
特點:
1.將多個view顯示在水平可滾動的列表中
2.只支持水平顯示 不支持垂直顯示
3.焦點view始終位於列表中央
注意事項:
1.在佈局文件中添加Gallery控件
2.在代碼中創建Adapter以顯示Gallery中的內容(這裏我們使用自定義Adapter)
3.添加Gallery的點擊事件監聽 並處理點擊時間
首先我們來寫Gallery佈局文件 並添加ImageView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spacing="10dip"
>
</Gallery>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
然後我們創建自定義Adapter(這裏可以寫爲內部類):
private class imageAdapter extends BaseAdapter{
private Context context; //先定義一個上下文內容
public imageAdapter(Context context) { //寫構造方法傳入一個context
this.context = context;
}
//定義一個數組存儲要顯示的圖片 這裏圖片使用了默認自帶的4張
public int[] image={R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher,};
@Override
public int getCount() {
// TODO Auto-generated method stub
return image.length; //第一個重寫的方法要返回數組的長度
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
} //第二個和第三個重寫的方法可以放着不用修改
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
//關鍵是第四個方法 它是動態創建圖片顯示的重點
@Override
public View getView(int position, View v, ViewGroup arg2) {
ImageView iv=new ImageView(context); //創建一個ImageView
iv.setImageResource(image[position]);
//顯示圖片的資源是來自於我們剛纔定義的數組
iv.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); //設置圖片的顯示方式是:內容包裹的
return iv; //最後返回這個view
}
}
最後我們將自定義的Adapter綁定到Gallery上面 併爲點擊Gallery中的圖片設置事件的監聽
public class Gallery1 extends Activity{
private Gallery ger=null;
private ImageView image=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
ger=(Gallery) findViewById(R.id.gallery);
image=(ImageView) findViewById(R.id.imageView1);
//設置適配器
final imageAdapter ia=new imageAdapter(Gallery1.this); //這裏適配器要設置爲Final 否則下面的方法不能調用
ger.setAdapter(ia); //將適配器綁定到Gallery上
//點擊圖片事件
ger.setOnItemClickListener(new OnItemClickListener() { //注意這裏的監聽方法
@Override
public void onItemClick(AdapterView<?> adapterView, View v, int position,
long arg3) {
int imgid=ia.image[position]; //這裏我們定義了一個變量來存儲適配器中定義的那一組圖片
image.setImageResource(imgid); //點擊事件的設定:當點擊某張圖片時 顯示的資源是image數組中此位置的圖片
}
});
ger.setSelection(2); //默認選中的是下標爲2的圖片(焦點)
}