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

来源:互联网 发布:pop软件中文版下载 编辑:程序博客网 时间:2024/05/24 05:01

项目中要求实现两行的水平滚动效果,当时想了很久是用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);}

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


效果图如下:










0 0
原创粉丝点击