Gallery的另类用法 类似GridView横向滚动

Gallery是个非常强大的控件,但是一般都把它当作显示图片之用。其实只要定制适配器,Gallery可以放进任何控件(显示图片就是放了ImageView)。我本来是想要GridView横向滚动的效果,但是实现起来好像比较麻烦,而Gallery本来就是横向滚动的,只要稍稍修改适配器即可。下面的例子把数据定死了,只需稍稍修改一下,把数据数组作为参数传入即可。
适配器代码:


package com.test;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.TextView;

public class GallleryAdapter extends BaseAdapter
{
	 private Context context;  
	 String[] s=new String[]{"第一集","第一集","第一集","第一集","第一集","第一集","第一集"};
	@Override
	public int getCount()
	{
		// TODO Auto-generated method stub
		return s.length;
	}
    public GallleryAdapter(Context c) {  
        context = c;  
        
    }  
	@Override
	public Object getItem(int position)
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int position)
	{
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		// TODO Auto-generated method stub
		TextView tv=new TextView(context);
		tv.setText(s[position]);
		tv.setLayoutParams(new Gallery.LayoutParams(120, 120));  
		return tv;
	}
	

}

Activity代码:


package com.test;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class AndroidTestActivity extends Activity {
    /** Called when the activity is first created. */
	Gallery gallery1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gallery1=(Gallery)findViewById(R.id.gallery1);
        gallery1.setAdapter(new GallleryAdapter(this));  
        gallery1.setOnItemSelectedListener(new OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView parent, View view, int position, long id)
			{
				// TODO Auto-generated method stub
				//默认情况下,选中或没选中的项,文字颜色都是灰色的,但是被选中的反而要淡一点
				//为了能更突出被选中项,把没选中的设为灰色,选中的设为红色
				Gallery ga=(Gallery)parent;
				for(int i=0;i parent)
			{
				// TODO Auto-generated method stub
				
			}});
    }
}

© 2011, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记