Android开发拖拉图片Gallery画廊组…

来源:互联网 发布:黑百通软件下载 编辑:程序博客网 时间:2024/04/29 01:33
Android开发拖拉图片Gallery画廊组件的使用--BaseAdapter



新建一个类ImageGalaryAdapter

//专门负责Gally填充的适配器类,使用组件的时候直接setAdapter
public class ImageGalaryAdapterextends BaseAdapter {
//通过构造方法赋值
private Contextcontext=null;
publicImageGalaryAdapter(Context context){
this.context=context;
}
//所要显示的一组图片组件
private int[] imgRes=newint[]{
R.drawable.ispic_a,
R.drawable.ispic_b,
R.drawable.ispic_c,
R.drawable.ispic_d,
R.drawable.ispic_e
};
public int getCount(){
//资源的数量
returnthis.imgRes.length;
}

public Object getItem(int arg0){
//取出每一个图片组件的编号
returnthis.imgRes[arg0];
}

public long getItemId(int arg0){
//取得我们组件的id 
returnthis.imgRes[arg0];
}

public View getView(int arg0,View arg1, ViewGroup arg2) {
//关键操作
//将资源设置到一个组件之中,很明显这个组件就是ImageView组件
ImageView img=newImageView(this.context);
//img.setBackgroundColor(0xFFFFFFFF);
//设置我们制定的图片文件
img.setImageResource(this.imgRes[arg0]);
//设置我们图片的位置
img.setScaleType(ImageView.ScaleType.CENTER);
img.setLayoutParams(newGallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
return img;
}

}

.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
  android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">
  <Gallery 
      android:id="@+id/myGallery"
      android:gravity="center_vertical"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:spacing="3px"/>
   

</LinearLayout>

.java

packagecom.example.galarydemo1;

importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.view.Menu;
importandroid.view.View;
importandroid.widget.AdapterView;
importandroid.widget.AdapterView.OnItemClickListener;
importandroid.widget.Gallery;
importandroid.widget.Toast;

public class MainActivityextends Activity {
private GallerymyGallery=null;
@Override
protected void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.myGallery=(Gallery)super.findViewById(R.id.myGallery);
//设置我们显示的内容
this.myGallery.setAdapter(newImageGalaryAdapter(this));
//为我们的画廊添加事件
this.myGallery.setOnItemClickListener(newImageGallyAdapterImp());
}

private classImageGallyAdapterImp implements OnItemClickListener{

public voidonItemClick(AdapterView<?> parent,View view, int position,
long id) {
//使用Toast显示用户选择的是哪一张图片
Toast.makeText(MainActivity.this,"您选择的是"+String.valueOf(position+1)+"张图片",Toast.LENGTH_SHORT).show();
}
}

}
0 0
原创粉丝点击