<?xml version="1.0" encoding="utf-8"?>

<resources>
<declare-styleable name="GalleryTheme">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
[/sourcecode]

Now edit your main.xml in res/layout folder

[sourcecode language="xml"]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/examplegallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
[/sourcecode]

Now your java code should looks like

[sourcecode language="java"]
package com.pack.gallery;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GalleryExample extends Activity {

private Gallery gallery;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));

gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Displaying the position when the gallery item in clicked
Toast.makeText(GalleryExample.this, "Position=" + position, Toast.LENGTH_SHORT).show();
}
});

}

public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;

// Adding images.
private Integer[] Imgid = {
R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4, R.drawable.a_5, R.drawable.a_6, R.drawable.a_7
};

public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}

public int getCount() {
return Imgid.length;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);

imgView.setImageResource(Imgid[position]);
// Fixing width & height for image to display
imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);

return imgView;
}
}

}

arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()