user2151017 user2151017 - 3 months ago 13
Android Question

How to add controls inside android grid

How can I add controls inside android grid layout so that it appears in each row according to data binding.

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/favorites_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00ff00"
android:rowCount="2"
android:columnCount="2">
<Button
android:text="Cell 0"
android:layout_row="0"
android:layout_column="0"
android:textSize="14dip" />
<Button
android:text="Cell 1"
android:layout_row="0"
android:layout_column="1"
android:textSize="14dip" />

<Button
android:text="Cell 2"
android:layout_row="1"
android:layout_column="0"
android:textSize="14dip" />
<Button
android:text="Cell 3"
android:layout_row="1"
android:layout_column="1"
android:textSize="14dip" />
</GridLayout>


I want this to be dynamic, without specifying row number.Please help.

Answer

Can't say that Android Binding support such kind of things. The best way so far is to use GridView with custom adapter or RecycleView with GridLayoutManager.

Here is an example of GridView adapter:

// create a new Button for each cell
public View getView(int position, View convertView, ViewGroup parent) {
   Button btn;
   if (convertView == null) {
       final Context context = parent.getContext();
       btn = new Button(context);
       btn.setLayoutParams(new GridView.LayoutParams(
               ViewGroup.LayoutParams.WRAP_CONTENT,
               ViewGroup.LayoutParams.WRAP_CONTENT)
       );
       btn.setPadding(8,8,8,8);
       btn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               Toast.makeText(context, "Button " + view.getTag() + " clicked", Toast.LENGTH_SHORT).show();
           }
       });
     } else {
         btn = (Button) convertView;
     }

     btn.setText("Cell " + position]);
     btn.setTag(position);
     return btn;
}
Comments