Android實現橫向滑動的GridView
阿新 • • 發佈:2018-12-31
因為專案中需要展示一組資料,要求為每頁最初展示五個資料,多出來的橫向滑動顯示,效果如下圖
效果就是這樣,這是一個答題介面,利用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展現方式
這樣就實現了首頁顯示5個選項,多餘的選項橫向滑動顯示出來。可以根據自己專案的需求來修改上面程式碼。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);//總長度