HorizontalScrollView



     由于移动设备物理显示空间一般有限,不可能一次性的把所有要显示的内容都显示在屏幕上。所以各大平台一般会提供一些可滚动的视图来向用户展示数据。Android平台框架中为我们提供了诸如ListView、GirdView、ScrollView等滚动视图控件,这几个视图控件也是我们平常使用最多的。我下面介绍一下HorizontalScrollView的使用和需要注意的点

     HorizontalScrollView是一个 FrameLayout  , 这意味着你只能在它下面放置一个子控件,这个子控件可以包含很多数据内容。有可能这个子控件本身就是一个布局控件,可以包含非常多的其他用来展示数据的控件。这个布局控件一般使用的是一个水平布局的 LinearLayout   。TextView也是一个可滚动的视图控件,所以一般不需要HorizontalScrollView

     下面介绍一个HorizontalScrollView中包含许多图片,并且可以滚动浏览的示例
[java]  view plain copy
  1.  @Override  
  2.  protected void onCreate(Bundle savedInstanceState) {  
  3.        super.onCreate(savedInstanceState);  
  4.       setContentView(R.layout. activity_main);  
  5.         
  6.        mLinearLayout = (LinearLayout) findViewById(R.id.mygallery);  
  7.         
  8.       File externalDir = Environment. getExternalStorageDirectory();  
  9.       String photosPath = externalDir.getAbsolutePath() + "/test/";  
  10.       File photosFile = new File(photosPath);  
  11.         
  12.        for (File photoFile : photosFile.listFiles()) {  
  13.               mLinearLayout.addView(getImageView(photoFile.getAbsolutePath()));  
  14.       }  
  15.         
  16. }  
  17.   
  18.  private View getImageView(String absolutePath) {  
  19.         
  20.       Bitmap bitmap = decodeBitmapFromFile(absolutePath, 200200);  
  21.     LinearLayout layout = new LinearLayout(getApplicationContext());  
  22.     layout.setLayoutParams( new LayoutParams(250250));  
  23.     layout.setGravity(Gravity. CENTER);  
  24.       
  25.       ImageView imageView = new ImageView(this);  
  26.       imageView.setLayoutParams( new LayoutParams(200,200));  
  27.       imageView.setScaleType(ImageView.ScaleType. CENTER_CROP);  
  28.       imageView.setImageBitmap(bitmap);  
  29.       layout.addView(imageView);  
  30.         
  31.        return layout;  
  32. }  
  33.   
  34.  private Bitmap decodeBitmapFromFile(String absolutePath, int reqWidth, int reqHeight) {  
  35.     Bitmap bm = null;  
  36.       
  37.      // First decode with inJustDecodeBounds=true to check dimensions  
  38.      final BitmapFactory.Options options = new BitmapFactory.Options();  
  39.      options. inJustDecodeBounds = true ;  
  40.      BitmapFactory. decodeFile(absolutePath, options);  
  41.       
  42.      // Calculate inSampleSize  
  43.      options. inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);  
  44.       
  45.      // Decode bitmap with inSampleSize set  
  46.      options. inJustDecodeBounds = false ;  
  47.      bm = BitmapFactory. decodeFile(absolutePath, options);  
  48.       
  49.      return bm;   
  50. }  
  51.   
  52.  private int calculateInSampleSize(Options options, int reqWidth,  
  53.               int reqHeight) {  
  54.      // Raw height and width of image  
  55.      final int height = options.outHeight;  
  56.      final int width = options.outWidth;  
  57.      int inSampleSize = 1;  
  58.          
  59.      if (height > reqHeight || width > reqWidth) {  
  60.       if (width > height) {  
  61.        inSampleSize = Math. round((float)height / ( float)reqHeight);    
  62.       } else {  
  63.        inSampleSize = Math. round((float)width / ( float)reqWidth);    
  64.       }    
  65.      }  
  66.       
  67.      return inSampleSize;   
  68. }  

     要显示的图片放在外置SDCard中test目录下,上面的示例程序只是显示了一张张大图片的缩略版本,对这方面不懂的可以参看http://blog.csdn.net/tibib/article/details/8726486
      HorizontalScrollView还可以设置滚动到一个指定的位置(x,0),它的子控件也会跟随着滚动。
[java]  view plain copy
  1. new Handler().postDelayed(new Runnable() {  
  2.     @Override  
  3.     public void run() {  
  4.         // 水平直接滚动800px,如果想效果更平滑可以使用smoothScrollTo(int x, int y)  
  5.         hsv.scrollTo(8000);  
  6.     }  
  7. }, 2000);  

效果大致如下


HorizontalScrollView实现Gallery效果

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

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


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

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


Activity类

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

自定义HSVLayout.java

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.hsv;  
  2.   
  3. import java.util.Map;  
  4.   
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.util.AttributeSet;  
  8. import android.view.View;  
  9. import android.widget.LinearLayout;  
  10. import android.widget.Toast;  
  11.   
  12. public class HSVLayout extends LinearLayout {  
  13.   
  14.     private HSVAdapter adapter;  
  15.     private Context context;  
  16.   
  17.     public HSVLayout(Context context, AttributeSet attrs) {  
  18.         super(context, attrs);  
  19.         this.context = context;  
  20.     }  
  21.   
  22.     public void setAdapter(HSVAdapter adapter) {  
  23.         this.adapter = adapter;  
  24.         for (int i = 0; i < adapter.getCount(); i++) {  
  25.             final Map<String, Object> map = adapter.getItem(i);  
  26.             View view = adapter.getView(i, nullnull);  
  27.             view.setPadding(100100);  
  28.             // 为视图设定点击监听器  
  29.             view.setOnClickListener(new OnClickListener() {  
  30.                 @Override  
  31.                 public void onClick(View v) {  
  32.                     Toast.makeText(context, "您选择了" + map.get("index"),  
  33.                             Toast.LENGTH_SHORT).show();  
  34.                     Intent intent = new Intent();  
  35.                     intent.setAction(AppConstant.UPDATE_IMAGE_ACTION);  
  36.                     intent.putExtra("index", (Integer)map.get("index"));  
  37.                     context.sendBroadcast(intent);  
  38.                       
  39.                 }  
  40.             });  
  41.             this.setOrientation(HORIZONTAL);  
  42.             this.addView(view, new LinearLayout.LayoutParams(  
  43.                     /*LayoutParams.WRAP_CONTENT*/300, LayoutParams.WRAP_CONTENT));  
  44.         }  
  45.     }  
  46. }  
还需要定义一个适配器HSVAdapter.java

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

main.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.   
  7.     <ImageSwitcher  
  8.         android:id="@+id/image_switcher"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="400dp" />  
  11.   
  12.     <HorizontalScrollView  
  13.         android:id="@+id/hsv"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:scrollbars="none" >  
  17.   
  18.         <com.example.hsv.HSVLayout  
  19.             android:id="@+id/movieLayout"  
  20.             android:layout_width="wrap_content"  
  21.             android:layout_height="wrap_content" />  
  22.     </HorizontalScrollView>  
  23.   
  24. </LinearLayout>  

hsv.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  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.   
  7.     <com.example.hsv.ImageViewBorder  
  8.         android:id="@+id/movie_image"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="400dp"  
  11.         android:layout_alignParentBottom="true"  
  12.         xmz:BorderColor="GRAY" />  
  13.   
  14. </RelativeLayout>  


HorizontalScrollView 去掉滚动条 用按钮控制滚动方向

在默认情况下,HorizontalScrollView控件里面的内容在滚动的情况下,会出现滚动条,为了去掉滚动条,只需要在<HorizontalScrollView/>里面加一句 android:scrollbars="none"。

如果想实现在代码里面,点击左(右)按钮【btnLeft(btnRight)】,滚动条里面的内容会向左向右滚动【horizontalScrollViewMM】。代码如下:

滚动条向左滚动:

btnLeft.setOnClickListener( new View.onClickListener(){

horizontalScrollViewMM.arrowScroll(View.FOCUS_LEFT);

});

滚动条向右滚动:

btnRight.setOnClickListener( new View.onClickListener(){

horizontalScrollViewMM.arrowScroll(View.FOCUS_RIGHT);

});

其中:arrowScroll方法:

public boolean arrowScroll (int direction)

响应点击左右箭头时对滚动条的处理。

参数

direction The direction corresponding to the arrow key that was pressed箭头按键所表示的方向

返回值

若此事件成功完成,则返回true;否则返回false。

HorizontalScrollView还有个方法你可能用得上:

public final void smoothScrollBy (int dx, int dy)

类似scrollBy(int, int),但是呈现平滑滚动,而非瞬间滚动(译者注:瞬间滚动——指不显示滚动过程,直接显示滚动后达到的位置)。

参数

dx 要滚动的X轴像素差值(译者注:横向像素差值)

dy 要滚动的Y轴像素差值(译者注:纵向像素差值)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值