大家好!已經第11天囉!這篇要分享GridView元件,GridView的UI設計在許多app裡是很常見的元件,GridView常被當作主頁面設計,由於GridView有清單式、方格式、圖片與文字搭配的特色,還有按鈕的觸發功能,在講求設計美感與實用功能的App設計裡,GridView極符合現今趨勢。那我們現在就來看GridView的介紹吧!
GridView英文可以拆分為兩個單字Grid-View,中文意思為格子(Grid)、View(視圖),我把GridView稱作一格格的畫面,GridView和ListView的差別為GridView為二維的排列方式,可以為欄可以為列又或者同時並存,反之,ListView是定義為可滑動的垂直清單意思是指有單方向的排列(定義參見、ListView樣式參見)。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<GridView
android:id="@+id/gvShow"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="2"
/>
</LinearLayout>
android:numColumns="2"
為了要設定Adapter,所以需要先前準備好要加入的資料,這邊創建String物件的陣列
private GridView gvShow;
private String[] fruit_name=new String[]{"Apple","Banana","Orange","Grape","Strawberry"};
一樣需要找元件,快速略過~
private void findViews () {
gvShow = (GridView) findViewById(R.id.gvShow);
spinner=(Spinner)findViewById(R.id.spinner);
}
Toast顯示短訊,建立setToast方法,日後方便重複使用與維護
private void setToast (String text){
Toast.makeText(MainActivity.this,
text, Toast.LENGTH_SHORT).show();
}
設計GridView偵聽器,在adapterView中尋找view物件得到的名稱
private void setListener() {
gvShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView,
View view, int position, long id) {
String msg = adapterView.getItemAtPosition(position).toString();
setToast(msg);
}
});
建立ArrayAdapter物件存放以String為主的物件
ArrayAdapter <String> adapter=new ArrayAdapter<String> (this,
android.R.layout.simple_list_item_1,fruit_name);
gvShow.setAdapter(adapter);
完整程式碼
public class MainActivity extends AppCompatActivity {
private GridView gvShow;
private String[] fruit_name=new String[]{"Apple","Banana","Orange","Grape","Strawberry"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
setAdapter();
setListener();
}
private void setAdapter(){
ArrayAdapter <String> adapter=
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,fruit_name);
gvShow.setAdapter(adapter);
}
private void setListener() {
gvShow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick
(AdapterView<?> adapterView, View view, int position, long id) {
String msg = adapterView.getItemAtPosition(position).toString();
setToast(msg);
}
});
}
private void setToast (String text){
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
}
private void findViews () {
gvShow = (GridView) findViewById(R.id.gvShow);
}
}
若文章有誤,歡迎大家提出建議。
Thank you for your time.