因为项目中需要展示一组数据,要求为每页最初展示五个数据,多出来的横向滑动显示,效果如下图
效果就是这样,这是一个答题界面,利用ViewPager实现,点击GridView中的选项跳转到下一题,其中1,2,3,4,5或A,B,C,D,E的Answer按钮为服务器返回的值,上面的题其实是一个WebView,首先先画布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_weight="1">
<WebView
android:id="@+id/web_view_question"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_weight="10"
android:background="#f1f1f1">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent">
<GridView
android:id="@+id/grid_view_answer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="spacingWidthUniform"/>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
</LinearLayout>
其中要实现横向的GridView首先要在外层包裹一层HorizontalScrollView,里面包裹一层线性布局,线性布局里面加载GridView,然后代码中实现GridView展现方式
view = LayoutInflater.from(this)
.inflate(R.layout.question_web_view, null);
WebView webView = (WebView) view.findViewById(R.id.web_view_question);
//LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.question_answer_ll);
webView.loadDataWithBaseURL(null, data.get(position).getHtmlContent(), "text/html", "utf-8", null);
webView.getSettings().setDisplayZoomControls(false);
GridView gridView = (GridView) view.findViewById(R.id.grid_view_answer);
gridView.setChoiceMode(GridView.CHOICE_MODE_SINGLE);
int size = data.get(pos).getOptionNum();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
float density = dm.density;
int everyWidth = dm.widthPixels;
Log.e("OptionNum", "instantiateItem: " + data.get(pos).getOptionNum());
int allWidth = (int) (50 * size * density);
int itemWidth = (int) (50 * density);
if (data.get(pos).getOptionNum() >= 5) {
allWidth = everyWidth / 5 * data.get(pos).getOptionNum();
itemWidth = everyWidth / 5;
} else {
allWidth = everyWidth;
itemWidth = everyWidth / data.get(pos).getOptionNum();
}
LayoutParams params = new LayoutParams(
allWidth, LayoutParams.MATCH_PARENT);
gridView.setLayoutParams(params);// 设置GirdView布局参数
gridView.setColumnWidth(itemWidth);// 列表项宽
gridView.setStretchMode(GridView.NO_STRETCH);
gridView.setNumColumns(size);//总长度
这样就实现了首页显示5个选项,多余的选项横向滑动显示出来。可以根据自己项目的需求来修改上面代码。