HorizontalScrollView的写法

今天去改了改app的bug,唉,多的惨不忍睹啊,期限内估计是做不完了,唉~
白天在做一个画廊,之前的coder用的是Gallery这个类,不过我写的时候发现类已经过时了,搜了一下发现在api版本16以后就改用HorizontalScrollView来做画廊了,具体代码如下:

需要注意的是HorizontalScrollView本质是一个FrameLayout,所以其包含的子元素只能有一个才能有效的显示

布局文件main.xml


<HorizontalScrollView
        android:layout_width="wrap_content"
        android:layout_height = "wrap_content"
>

<com.hh.movie.view.HSVLinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

/>

</HorizontalScrollView>

继承LinearLayout的自定义类

class HSVLinearLayout extends LinearLayout

{
/画廊的适配器/

  private HSVAdapter adapter;  
private Context context;  

public HSVLinearLayout(Context context, AttributeSet attrs) {  
    super(context, attrs);  
    this.context = context;  
}  
//这个方法是关键,不断的重绘把HSVLinearLayout填满!!!
public void setAdapter(HSVAdapter adapter)

{

for(int i=0;i<adapter.count();i++)

{

View view = adapter.getView(i,null,null);

//设置左右边距为10

view.setPadding(10,0,10,0);

//对齐

this.setOrientation(HORIZONTAL);
this.addView(view,new LinearLayout.LayoutParams(  
                /*LayoutParams.WRAP_CONTENT*/300, LayoutParams.WRAP_CONTENT));

}
}
}
//画廊适配器
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;  
}  

}
//适配器的布局文件movie.xml,只有一个ImageView
android:id=“@+id/movie_image”;
android:layout_width=“wrap_content”;
android:layout_height =“wrap_content”;
/>
全文借鉴此处感谢原作者的贡献

  • Fragent
    Fragment使用起来不要给它设置空构造,否则运行起来报错。

  • FramLayout
    这个布局在做button的时候很好用,特别是做点赞和计数继承在一个“按钮”上的时候`

    android:layout_width=“wrap_content”;
    android:layout_width=“wrap_content”;

你可能感兴趣的:(HorizontalScrollView的写法)