MainActivity如下:
package cc.cv; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.app.Activity; import android.content.Context; /** * Demo描述: * HorizontalScrollView的简单使用 * * 在Google文档中Gallery已经弃用.推荐使用HorizontalScrollView和ViewPager. * ViewPager用过不少,HorizontalScrollView倒是很少使用.所以在此学习. * * Demo说明: * 1 布局文件很简单,在HorizontalScrollView中嵌套了一个LinearLayout * 2 在代码中只需将自定义的View添加到LinearLayout中即可. * 这样就可以实现水平滑动了. * */ public class MainActivity extends Activity { private Context mContext; private int [] mPhotosIntArray; private LayoutInflater mLayoutInflater; private LinearLayout mGalleryLinearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initView(); initData(); } private void initView(){ mContext=this; mGalleryLinearLayout=(LinearLayout) findViewById(R.id.galleryLinearLayout); mLayoutInflater=LayoutInflater.from(mContext); } private void initData(){ mPhotosIntArray=new int[]{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e,R.drawable.f,R.drawable.g,R.drawable.h}; View itemView=null; ImageView imageView=null; TextView textView; for (int i = 0; i < mPhotosIntArray.length; i++) { itemView=mLayoutInflater.inflate(R.layout.gallery_item, null); imageView=(ImageView) itemView.findViewById(R.id.imageView); textView=(TextView) itemView.findViewById(R.id.textView); imageView.setImageResource(mPhotosIntArray[i]); textView.setText("This is "+(i+1)); mGalleryLinearLayout.addView(itemView); } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <HorizontalScrollView android:layout_width="match_parent" android:layout_height="150dip" android:layout_centerInParent="true" android:scrollbars="horizontal" > <LinearLayout android:id="@+id/galleryLinearLayout" android:layout_width="wrap_content" android:layout_height="fill_parent" android:gravity="center_vertical" > </LinearLayout> </HorizontalScrollView> </RelativeLayout>
gallery_item.xml如下:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView" android:layout_width="80dip" android:layout_height="80dip" android:layout_centerHorizontal="true" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/imageView" android:layout_centerHorizontal="true" android:layout_marginTop="8dip" /> </RelativeLayout>
HorizontalScrollView的使用示例,布布扣,bubuko.com
时间: 2024-10-04 22:13:25