android 让gallery中图片默认居左显示

    最近项目中有用到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;
		}
	}
}

下面是效果图


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值