android GridView两行水平滚动实现效果

项目中要求实现两行的水平滚动效果,当时想了很久是用listview实现呢还是用gridview实现,最后决定用gridview实现,如下:

首先重写gridview:

public class MyGridView extends GridView {

    public MyGridView(Context context) {
        super(context);
    }

    public MyGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO 自动生成的构造函数存根
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // TODO 自动生成的方法存根
        int expandSpec = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}
 
 然后在xml布局中: 

<HorizontalScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none"
    >
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <com.xxx.MyGridView
            android:id="@+id/gridView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:verticalSpacing="10dp"
            android:stretchMode="columnWidth"
            >
        </com.xxx.MyGridView>
    </LinearLayout>
</HorizontalScrollView>

在代码中这样:

homeReqAdapter.updata(context, typeBean.data);//这是我定义的adapter加载数据,
int count = homeReqAdapter.getCount();
int columns = (count % 2 == 0) ? count / 2 : count / 2 + 1;
gridView1.setAdapter(homeReqAdapter);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columns * dm.widthPixels / NUM,
        LinearLayout.LayoutParams.WRAP_CONTENT);
gridView1.setLayoutParams(params);
gridView1.setColumnWidth(dm.widthPixels / NUM);
gridView1.setStretchMode(GridView.NO_STRETCH);
if (count <= 3) {
    gridView1.setNumColumns(count);
} else {
    gridView1.setNumColumns(columns);
}

实现上面的就可以了!主要的代码都在这里了,小细节都需要自己去完善!


效果图如下:










  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值