记得之前有个Gallery,但是这个以后被Google放弃了,用过的Gallery的人肯定知道不好用,现在更多的是使用ViewPager或 HorizontalScrollView,今天说下 HorizontalScrollView的简单使用吧,之前项目中都没用到过这个控件,以为是和listview的1样使用,后才才发现HorizontalScrollView没有甚么setAdapter()方法,哪怎样绑定1些资源到HorizontalScrollView控件上呢?换个思路,我们可以里面加1个LinearLayout控件,由于LinearLayout它有方向的属性,现在新建1个Android项目/HorizontalDemo,
activity_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:id="@+id/hsv"
android:layout_width="fill_parent"
android:layout_height="180dp"
android:layout_marginTop="20dp"
>
<LinearLayout
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
></LinearLayout>
</HorizontalScrollView>
</RelativeLayout>
MainActivity.java
package com.example.horizontaldemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private HorizontalScrollView hsv;
private LinearLayout ll;
private int[] mImgIds;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hsv = (HorizontalScrollView) findViewById(R.id.hsv);
ll = (LinearLayout) findViewById(R.id.ll);
initData();
initView();
}
private void initView() {
for(int i=0;i<mImgIds.length;i++){
View itemView = getLayoutInflater().inflate(R.layout.item, null);
ImageView iv = (ImageView) itemView.findViewById(R.id.iv);
TextView tv_name = (TextView) itemView.findViewById(R.id.tv_name);
iv.setImageResource(mImgIds[i]);
tv_name.setText("妹1个");
ll.addView(itemView);
}
}
private void initData()
{
mImgIds = 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, R.drawable.l };
}
}
item.xml
<?xml version="1.0" encoding="utf⑻"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv"
android:layout_width="90dp"
android:layout_height="90dp"
/>
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
效果图:
在这感谢http://blog.csdn.net/lmj623565791/article/details/38140505博客的图片资源