最近项目中有用到gallery,要求默认是在最左边显示出来的,也试过
gallery.setSelection(position) ;但是对于初始状态没有图片的话,就不能这样用了,最后想到一个办法是设置左边距为负数,这样就可以达到默认居左的显示效果。
package com.example.test2;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this));// 设置图片适配器
MarginLayoutParams layoutParams = (MarginLayoutParams) gallery.getLayoutParams();
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
layoutParams.setMargins(-width*2/3, 0, 0, 0);
// 设置监听器
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(MainActivity.this, "点击了第" + arg2 + "张图片",
Toast.LENGTH_LONG).show();
}
});
}
class ImageAdapter extends BaseAdapter {
private Context context;
// 图片源数组
private Integer[] imageInteger = { R.drawable.cygj, R.drawable.hcql,
R.drawable.ic_launcher, R.drawable.jcgl };
public ImageAdapter(Context c) {
context = c;
}
@Override
public int getCount() {
return imageInteger.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageInteger[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(136, 88));
return imageView;
}
}
}
下面是效果图