【显示效果】
1.界面布局---gallery控件
【main.xml】
<?xml version="1.0" encoding="utf-8"?>
<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gallery1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</Gallery>
2.显示图片:准备3张图片,放在res/drawable-hdpi文件夹中
3.显示适配器
【Adpater_image.java】
package com.example.xiangbu;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class Adapter_image extends BaseAdapter {
public Context myContext;
public Integer[] imgArray = { R.drawable.p1, R.drawable.p2, R.drawable.p3 };
public Adapter_image(Context c) { // context:上下文,环境
myContext = c;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return imgArray.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return imgArray[position];
}
@Override
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 img = new ImageView(myContext);
img.setImageResource(imgArray[position]);// 资源
img.setLayoutParams(new Gallery.LayoutParams(320, 480));// param:参数
img.setScaleType(ImageView.ScaleType.FIT_CENTER);
return img;
}
}
4.显示主界面:在里面声明Gallery,并设置Adapter
【MainActivity.java】
package com.example.xiangbu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.Toast;
@SuppressWarnings("deprecation")
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 声明gallery并设置adapter
@SuppressWarnings("deprecation")
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new Adapter_image(this));
/* gallery.setBackgroundResource(R.drawable.p4); */
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"第" + (arg2 + 1) + "号图片", Toast.LENGTH_LONG).show();
}
});
}
}