There is such an example of forming a GridView based on the transferred array of scalars.

http://startandroid.ru/ru/uroki/vse-uroki-spiskom/116-urok-57-gridview-i-ego-atributy.html

MainActivity.java:

public class MainActivity extends Activity { String[] data = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"}; GridView gvMain; ArrayAdapter<String> adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tvText, data); gvMain = (GridView) findViewById(R.id.gvMain); gvMain.setAdapter(adapter); adjustGridView(); } private void adjustGridView() { gvMain.setNumColumns(3); } } 

item.xml:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/rect" android:orientation="vertical"> <TextView android:id="@+id/tvText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:minHeight="40dp" android:textSize="20sp" android:text=""> </TextView> </LinearLayout> 

result:

enter image description here

and how to implement a more complex structure, where the array consists not of scalars, but arrays of 2 or more elements?

added:

I wanted to display a more complex fragment, for example item2.xml:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/rect" android:orientation="vertical"> <TextView android:id="@+id/tvText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:minHeight="40dp" android:textSize="20sp" android:text=""> </TextView> <TextView android:id="@+id/tvText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:minHeight="40dp" android:textSize="20sp" android:text=""> </TextView> </LinearLayout> 

How to connect the elements of the transmitted array with R.id.tvText and R.id.tvText2 ?

  • Show an example of what you want to transfer to the GridView . I personally do not understand what will mean a более сложную структуру, где массив состоит не из скаляров, а массивов из 2х и более элементов - Vladyslav Matviienko
  • @metalurgus, added a question - ravend

2 answers 2

To work with GridView, as well as when working with any list, an adapter is used that receives data from any source (database, array, GSON, HashMap) and gives it to the list. In this case, for the GridView.

Four adapter methods are critical for operation -

 public int getCount() { } //возвращает количество элементов, чтобы список знал, сколько элементов ему нужно построить public Object getItem(int position) { } //возвращает данные элемента списка из источника - из List, ArrayList, БазаДанных и т.д. public long getItemId(int position) { } //возвращает ID элемента списка. Обычно равен самой позиции (return position). 

and the most important method where element formation takes place

 public View getView(final int position, View convertView, ViewGroup parent) { } 

More details can be found here http://startandroid.ru/ru/uroki/vse-uroki-spiskom/113-urok-54-kastomizatsija-spiska-sozdaem-svoj-adapter.html

here http://developer.alexanderklimov.ru/android/theory/adapters.php

and here http://metanit.com/java/android/5.1.php

An adapter is created by creating an object, like

 MyAdapter myAdapter = new MyAdapter(); 

where the class MyAdapter is inherited from the desired ancestor. for example

 public class MyAdapter extends BaseAdapter { } 

and is assigned to the gridview via the method

 gridView.setAdapter(myAdapter); 

In general, the topic of adapters must be mastered very well, because this is a very important part of the work of the Android programmer. Good luck in learning!

Added: Here is an example of a "complex" item:

  @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; ViewHolder viewHolder; if (convertView == null) { view = activity.getLayoutInflater().inflate(R.layout.item_time, null); viewHolder = new ViewHolder(); viewHolder.tvTime = (TextView) view.findViewById(R.id.tvTime); viewHolder.ib_Ticket = (ImageButton) view.findViewById(R.id.ib_Ticket); viewHolder.llItemTime = (LinearLayout) view.findViewById(R.id.llItemTime); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } viewHolder.tvTime.setText(getItem(position).getTime()); viewHolder.llItemTime.setBackgroundDrawable(activity.getResources().getDrawable(R.drawable.button_orange_gray_on)); viewHolder.llItemTime.setClickable(true); viewHolder.ib_Ticket.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTicketBuy(position); } }); return view; } 
  • supplemented the question. Is it possible to complicate the structure of the item-layout, and how, in this case, to link several TextViews with the values ​​from the transmitted array? - ravend
  • can. no problem. added an example to the answer. - AndrewGrow
  • I do not understand how to call it? in my example adapter = new ArrayAdapter<String>(this, R.layout.item, R.id.tvText, data); passed the layout, Id and array. How to pass such an array: {'text1', '/ img1.png', 'text2', '/ img2.png'} or more complex {{'text1', '/ img1.png'}, {'text2', '/img2.png'}}? - ravend
  • Use the spelling of a custom adapter - a successor to BaseAdapter - AndrewGrow
  • one
    @ravend, you just need to create your own class, which will contain 2 fields of type String, and transfer to the adapter an array of these objects - Vladyslav Matviienko

If we plan to use this code, it is obvious that we should display any "structure" in a flat array String[] data (simply because the adapter accepts a flat array as a parameter)

  • not necessary. The custom adapter accepts at least a bald trait :-) - Vladyslav Matviienko