由于移动设备物理显示空间一般有限,不可能一次性的把所有要显示的内容都显示在屏幕上。所以各大平台一般会提供一些可滚动的视图来向用户展示数据。Android平台框架中为我们提供了诸如ListView、GirdView、ScrollView等滚动视图控件,这几个视图控件也是我们平常使用最多的。我下面介绍一下HorizontalScrollView的使用和需要注意的点
HorizontalScrollView是一个
FrameLayout ,
这意味着你只能在它下面放置一个子控件,这个子控件可以包含很多数据内容。有可能这个子控件本身就是一个布局控件,可以包含非常多的其他用来展示数据的控件。这个布局控件一般使用的是一个水平布局的
LinearLayout
。TextView也是一个可滚动的视图控件,所以一般不需要HorizontalScrollView
下面介绍一个HorizontalScrollView中包含许多图片,并且可以滚动浏览的示例
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout. activity_main);
- mLinearLayout = (LinearLayout) findViewById(R.id.mygallery);
- File externalDir = Environment. getExternalStorageDirectory();
- String photosPath = externalDir.getAbsolutePath() + "/test/";
- File photosFile = new File(photosPath);
- for (File photoFile : photosFile.listFiles()) {
- mLinearLayout.addView(getImageView(photoFile.getAbsolutePath()));
- }
- }
- private View getImageView(String absolutePath) {
- Bitmap bitmap = decodeBitmapFromFile(absolutePath, 200, 200);
- LinearLayout layout = new LinearLayout(getApplicationContext());
- layout.setLayoutParams( new LayoutParams(250, 250));
- layout.setGravity(Gravity. CENTER);
- ImageView imageView = new ImageView(this);
- imageView.setLayoutParams( new LayoutParams(200,200));
- imageView.setScaleType(ImageView.ScaleType. CENTER_CROP);
- imageView.setImageBitmap(bitmap);
- layout.addView(imageView);
- return layout;
- }
- private Bitmap decodeBitmapFromFile(String absolutePath, int reqWidth, int reqHeight) {
- Bitmap bm = null;
- // First decode with inJustDecodeBounds=true to check dimensions
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options. inJustDecodeBounds = true ;
- BitmapFactory. decodeFile(absolutePath, options);
- // Calculate inSampleSize
- options. inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
- // Decode bitmap with inSampleSize set
- options. inJustDecodeBounds = false ;
- bm = BitmapFactory. decodeFile(absolutePath, options);
- return bm;
- }
- private int calculateInSampleSize(Options options, int reqWidth,
- int reqHeight) {
- // Raw height and width of image
- final int height = options.outHeight;
- final int width = options.outWidth;
- int inSampleSize = 1;
- if (height > reqHeight || width > reqWidth) {
- if (width > height) {
- inSampleSize = Math. round((float)height / ( float)reqHeight);
- } else {
- inSampleSize = Math. round((float)width / ( float)reqWidth);
- }
- }
- return inSampleSize;
- }
要显示的图片放在外置SDCard中test目录下,上面的示例程序只是显示了一张张大图片的缩略版本,对这方面不懂的可以参看http://blog.csdn.net/tibib/article/details/8726486
HorizontalScrollView还可以设置滚动到一个指定的位置(x,0),它的子控件也会跟随着滚动。
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- // 水平直接滚动800px,如果想效果更平滑可以使用smoothScrollTo(int x, int y)
- hsv.scrollTo(800, 0);
- }
- }, 2000);
效果大致如下
最近在学习Gallery发现在API Level 16以后已经不使用,废弃了这个肯定是有更好的来替代,查了下文档就发现HorizontalScrollView这个类;
HorizontalScrollView用于布局的容器,可以放置让用户使用滚动条查看的视图层次结构,允许视图结构比手机的屏幕大.。HorizontalScrollView 是一种 框架布局, 这意味着你可以将包含要滚动的完整内容的子视图放入该容器; 该子视图本身也可以是具有复杂层次结构的布局管理器。一般使用横向的 LinearLayout 作为子视图,使用户可以滚动其中显示的条目。
不要将 HorizontalScrollView 和 列表视图 组合使用, 因为列表视图有自己的滚动处理.更重要的是,组合使用会使列表视图针对大的列表所做的重要优化失效, 因为 HorizontalScrollView 会强制列表视图显示其所有条目,以使用由 HorizontalScrollView 提供滚动处理的容器。HorizontalScrollView 只支持水平方向的滚动。
以下是ImageSwitcher和HorizontalScrollView的组合效果图:
Activity类
- 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
- 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));
- }
- }
- }
- 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
- <?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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:xmz="http://xmz.com"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" >
- <com.example.hsv.ImageViewBorder
- android:id="@+id/movie_image"
- android:layout_width="wrap_content"
- android:layout_height="400dp"
- android:layout_alignParentBottom="true"
- xmz:BorderColor="GRAY" />
- </RelativeLayout>