Android控件之HorizontalScrollView代替Gallery

最近在学习Gallery发现在API Level 16以后已经不使用,废弃了这个肯定是有更好的来替代,查了下文档就发现HorizontalScrollView这个类;

HorizontalScrollView用于布局的容器,可以放置让用户使用滚动条查看的视图层次结构,允许视图结构比手机的屏幕大.。HorizontalScrollView 是一种 框架布局, 这意味着你可以将包含要滚动的完整内容的子视图放入该容器; 该子视图本身也可以是具有复杂层次结构的布局管理器。一般使用横向的 LinearLayout 作为子视图,使用户可以滚动其中显示的条目。


不要将 HorizontalScrollView 和 列表视图 组合使用, 因为列表视图有自己的滚动处理.更重要的是,组合使用会使列表视图针对大的列表所做的重要优化失效, 因为 HorizontalScrollView 会强制列表视图显示其所有条目,以使用由 HorizontalScrollView 提供滚动处理的容器。HorizontalScrollView 只支持水平方向的滚动。

以下是ImageSwitcher和HorizontalScrollView的组合效果图:


Activity类

  1. package com.example.viewgroupdemo;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import android.app.Activity;
  5. import android.content.BroadcastReceiver;
  6. import android.content.Context;
  7. import android.content.Intent;
  8. import android.content.IntentFilter;
  9. import android.os.Bundle;
  10. import android.view.View;
  11. import android.view.ViewGroup.LayoutParams;
  12. import android.widget.ImageSwitcher;
  13. import android.widget.ImageView;
  14. import android.widget.ViewSwitcher.ViewFactory;
  15. import com.example.hsv.AppConstant;
  16. import com.example.hsv.HSVAdapter;
  17. import com.example.hsv.HSVLayout;
  18. /**
  19. * 2013.10.12 类似图片浏览的例子
  20. *
  21. * @author Administrator
  22. *
  23. */
  24. public class MainActivity extends Activity implements ViewFactory {
  25. public ImageSwitcher imageSwitcher = null; // 图片切换
  26. private HSVLayout movieLayout = null;
  27. private HSVAdapter adapter = null;
  28. private IntentFilter intentFilter = null;
  29. private BroadcastReceiver receiver = null;
  30. private int nCount = 0;
  31. // pic in the drawable
  32. private Integer[] images = { R.drawable.pre0, R.drawable.pre1,
  33. R.drawable.pre2, R.drawable.pre3, R.drawable.pre4, R.drawable.pre5,
  34. R.drawable.pre6, R.drawable.pre7, R.drawable.pre8, R.drawable.pre9,
  35. R.drawable.pre10 };
  36. @Override
  37. public void onCreate(Bundle savedInstanceState) {
  38. super.onCreate(savedInstanceState);
  39. setContentView(R.layout.main);
  40. imageSwitcher = (ImageSwitcher) findViewById(R.id.image_switcher);
  41. imageSwitcher.setFactory(this);
  42. movieLayout = (HSVLayout) findViewById(R.id.movieLayout);
  43. adapter = new HSVAdapter(this);
  44. for (int i = 0; i < images.length; i++) {
  45. Map<String, Object> map = new HashMap<String, Object>();
  46. map.put("image", images[i]);
  47. // map.put("image", getResources().getDrawable(images[i]));
  48. map.put("index", (i+1));
  49. adapter.addObject(map);
  50. }
  51. movieLayout.setAdapter(adapter);
  52. // 设置当前显示的图片
  53. imageSwitcher.setImageResource(images[nCount]);
  54. }
  55. @Override
  56. protected void onPause() {
  57. // TODO Auto-generated method stub
  58. super.onPause();
  59. unregisterReceiver(receiver);
  60. }
  61. @Override
  62. protected void onResume() {
  63. // TODO Auto-generated method stub
  64. super.onResume();
  65. if (receiver == null) {
  66. receiver = new UpdateImageReceiver();
  67. }
  68. registerReceiver(receiver, getIntentFilter());
  69. }
  70. /**
  71. * 创建一个消息过滤器
  72. *
  73. * @return
  74. */
  75. private IntentFilter getIntentFilter() {
  76. if (intentFilter == null) {
  77. intentFilter = new IntentFilter();
  78. intentFilter.addAction(AppConstant.UPDATE_IMAGE_ACTION);
  79. }
  80. return intentFilter;
  81. }
  82. /**
  83. * 创建一个用于添加到视图转换器(ViewSwitcher)中的新视图
  84. */
  85. @Override
  86. public View makeView() {
  87. // TODO Auto-generated method stub
  88. ImageView imageView = new ImageView(getApplicationContext());
  89. imageView.setBackgroundColor(0xFF000000);
  90. imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
  91. imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
  92. LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
  93. return imageView;
  94. }
  95. class UpdateImageReceiver extends BroadcastReceiver{
  96. @Override
  97. public void onReceive(Context context, Intent intent) {
  98. // TODO Auto-generated method stub
  99. if(intent.getAction().equals(AppConstant.UPDATE_IMAGE_ACTION)){
  100. int index = intent.getIntExtra("index", Integer.MAX_VALUE);
  101. imageSwitcher.setImageResource(images[index-1]);
  102. System.out.println("UpdateImageReceiver----" + index);
  103. }
  104. }
  105. }
  106. }
package com.example.viewgroupdemo;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

import com.example.hsv.AppConstant;
import com.example.hsv.HSVAdapter;
import com.example.hsv.HSVLayout;

/**
 * 2013.10.12 类似图片浏览的例子
 * 
 * @author Administrator
 * 
 */
public class MainActivity extends Activity implements ViewFactory {

	public ImageSwitcher imageSwitcher = null; // 图片切换
	private HSVLayout movieLayout = null;
	private HSVAdapter adapter = null;
	private IntentFilter intentFilter = null;
	private BroadcastReceiver receiver = null;
	private int nCount = 0;
	// pic in the drawable
	private Integer[] images = { R.drawable.pre0, R.drawable.pre1,
			R.drawable.pre2, R.drawable.pre3, R.drawable.pre4, R.drawable.pre5,
			R.drawable.pre6, R.drawable.pre7, R.drawable.pre8, R.drawable.pre9,
			R.drawable.pre10 };

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		imageSwitcher = (ImageSwitcher) findViewById(R.id.image_switcher);
		imageSwitcher.setFactory(this);
		movieLayout = (HSVLayout) findViewById(R.id.movieLayout);
		adapter = new HSVAdapter(this);
		for (int i = 0; i < images.length; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("image", images[i]);
			// map.put("image", getResources().getDrawable(images[i]));
			map.put("index", (i+1));
			adapter.addObject(map);
		}
		movieLayout.setAdapter(adapter);
		// 设置当前显示的图片
		imageSwitcher.setImageResource(images[nCount]);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(receiver);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (receiver == null) {
			receiver = new UpdateImageReceiver();
		}
		registerReceiver(receiver, getIntentFilter());
	}

	/**
	 * 创建一个消息过滤器
	 * 
	 * @return
	 */
	private IntentFilter getIntentFilter() {
		if (intentFilter == null) {
			intentFilter = new IntentFilter();
			intentFilter.addAction(AppConstant.UPDATE_IMAGE_ACTION);
		}
		return intentFilter;
	}
	
	/**
	 * 创建一个用于添加到视图转换器(ViewSwitcher)中的新视图
	 */
	@Override
	public View makeView() {
		// TODO Auto-generated method stub
		ImageView imageView = new ImageView(getApplicationContext());
		imageView.setBackgroundColor(0xFF000000);
		imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
		imageView.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		return imageView;
	}
	
	class UpdateImageReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if(intent.getAction().equals(AppConstant.UPDATE_IMAGE_ACTION)){
				int index = intent.getIntExtra("index", Integer.MAX_VALUE);
				imageSwitcher.setImageResource(images[index-1]);
				System.out.println("UpdateImageReceiver----" + index);
			}
		}
		
	}
}

自定义HSVLayout.java

  1. package com.example.hsv;
  2. import java.util.Map;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.util.AttributeSet;
  6. import android.view.View;
  7. import android.widget.LinearLayout;
  8. import android.widget.Toast;
  9. public class HSVLayout extends LinearLayout {
  10. private HSVAdapter adapter;
  11. private Context context;
  12. public HSVLayout(Context context, AttributeSet attrs) {
  13. super(context, attrs);
  14. this.context = context;
  15. }
  16. public void setAdapter(HSVAdapter adapter) {
  17. this.adapter = adapter;
  18. for (int i = 0; i < adapter.getCount(); i++) {
  19. final Map<String, Object> map = adapter.getItem(i);
  20. View view = adapter.getView(i, null, null);
  21. view.setPadding(10, 0, 10, 0);
  22. // 为视图设定点击监听器
  23. view.setOnClickListener(new OnClickListener() {
  24. @Override
  25. public void onClick(View v) {
  26. Toast.makeText(context, "您选择了" + map.get("index"),
  27. Toast.LENGTH_SHORT).show();
  28. Intent intent = new Intent();
  29. intent.setAction(AppConstant.UPDATE_IMAGE_ACTION);
  30. intent.putExtra("index", (Integer)map.get("index"));
  31. context.sendBroadcast(intent);
  32. }
  33. });
  34. this.setOrientation(HORIZONTAL);
  35. this.addView(view, new LinearLayout.LayoutParams(
  36. /*LayoutParams.WRAP_CONTENT*/300, LayoutParams.WRAP_CONTENT));
  37. }
  38. }
  39. }
package com.example.hsv;

import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class HSVLayout extends LinearLayout {

	private HSVAdapter adapter;
	private Context context;

	public HSVLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
	}

	public void setAdapter(HSVAdapter adapter) {
		this.adapter = adapter;
		for (int i = 0; i < adapter.getCount(); i++) {
			final Map<String, Object> map = adapter.getItem(i);
			View view = adapter.getView(i, null, null);
			view.setPadding(10, 0, 10, 0);
			// 为视图设定点击监听器
			view.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Toast.makeText(context, "您选择了" + map.get("index"),
							Toast.LENGTH_SHORT).show();
					Intent intent = new Intent();
					intent.setAction(AppConstant.UPDATE_IMAGE_ACTION);
					intent.putExtra("index", (Integer)map.get("index"));
					context.sendBroadcast(intent);
					
				}
			});
			this.setOrientation(HORIZONTAL);
			this.addView(view, new LinearLayout.LayoutParams(
					/*LayoutParams.WRAP_CONTENT*/300, LayoutParams.WRAP_CONTENT));
		}
	}
}
还需要定义一个适配器HSVAdapter.java

  1. package com.example.hsv;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.Map;
  5. import com.example.viewgroupdemo.R;
  6. import android.content.Context;
  7. import android.view.LayoutInflater;
  8. import android.view.View;
  9. import android.view.ViewGroup;
  10. import android.widget.BaseAdapter;
  11. import android.widget.ImageView;
  12. /**
  13. * 为画廊定义适配器
  14. * @author Administrator
  15. *
  16. */
  17. public class HSVAdapter extends BaseAdapter {
  18. private List<Map<String,Object>> list;
  19. private Context context;
  20. public HSVAdapter(Context context){
  21. this.context=context;
  22. this.list=new ArrayList<Map<String,Object>>();
  23. }
  24. @Override
  25. public int getCount() {
  26. return list.size();
  27. }
  28. @Override
  29. public Map<String,Object> getItem(int location) {
  30. return list.get(location);
  31. }
  32. @Override
  33. public long getItemId(int arg0) {
  34. return arg0;
  35. }
  36. public void addObject(Map<String,Object> map){
  37. list.add(map);
  38. notifyDataSetChanged();
  39. }
  40. @Override
  41. public View getView(int location, View arg1, ViewGroup arg2) {
  42. View view = LayoutInflater.from(context).inflate(R.layout.movie,null);
  43. ImageView image=(ImageView)view.findViewById(R.id.movie_image);
  44. Map<String,Object> map=getItem(location); //获取当前的Item
  45. //image.setBackground((Drawable)map.get("image"));
  46. image.setBackgroundResource((Integer) map.get("image"));
  47. return view;
  48. }
  49. }
package com.example.hsv;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.example.viewgroupdemo.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

/**
 * 为画廊定义适配器
 * @author Administrator
 *
 */
public class HSVAdapter extends BaseAdapter {

	private List<Map<String,Object>> list;
	private Context context;
	public HSVAdapter(Context context){
		this.context=context;
		this.list=new ArrayList<Map<String,Object>>();
	}
	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Map<String,Object> getItem(int location) {
		return list.get(location);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	public void addObject(Map<String,Object> map){
		list.add(map);
		notifyDataSetChanged();
	}
	@Override
	public View getView(int location, View arg1, ViewGroup arg2) {
		View view = LayoutInflater.from(context).inflate(R.layout.movie,null);
		ImageView image=(ImageView)view.findViewById(R.id.movie_image);
		Map<String,Object> map=getItem(location); //获取当前的Item
		//image.setBackground((Drawable)map.get("image"));
		image.setBackgroundResource((Integer) map.get("image"));
		return view;
	}

}

main.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical" >
  6. <ImageSwitcher
  7. android:id="@+id/image_switcher"
  8. android:layout_width="match_parent"
  9. android:layout_height="400dp" />
  10. <HorizontalScrollView
  11. android:id="@+id/hsv"
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"
  14. android:scrollbars="none" >
  15. <com.example.hsv.HSVLayout
  16. android:id="@+id/movieLayout"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content" />
  19. </HorizontalScrollView>
  20. </LinearLayout>
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageSwitcher
        android:id="@+id/image_switcher"
        android:layout_width="match_parent"
        android:layout_height="400dp" />

    <HorizontalScrollView
        android:id="@+id/hsv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="none" >

        <com.example.hsv.HSVLayout
            android:id="@+id/movieLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </HorizontalScrollView>

</LinearLayout>

hsv.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:xmz="http://xmz.com"
  4. android:layout_width="wrap_content"
  5. android:layout_height="wrap_content" >
  6. <com.example.hsv.ImageViewBorder
  7. android:id="@+id/movie_image"
  8. android:layout_width="wrap_content"
  9. android:layout_height="400dp"
  10. android:layout_alignParentBottom="true"
  11. xmz:BorderColor="GRAY" />
  12. </RelativeLayout>
    </pre>  </li></ol></div><pre style="display: none;" class="html" name="code" snippet_file_name="blog_20131209_5_7352169" code_snippet_id="104591">
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值