How to add GridView Layout in android using Android Studio

0 2,401

GridView Layout in android

In this tut i will show you, how you can create GridView layout,GridView layout shows list items in two-dimensional (rows & columns) which is a scrollable Grid list.

Main activity

package exceptionbound.com.gridviewinandroid;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridView =(GridView)findViewById(R.id.gridView);
        gridView.setAdapter(new GridAdapter(MainActivity.this));

    }
}

class GridAdapter extends BaseAdapter{
    Context context;
    String string="123456789";

    public GridAdapter(Context c){
        context = c;
    }

    @Override
    public int getCount() {
        return string.length();
    }

    @Override
    public Object getItem(int position) {
        return string.charAt(position);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        TextView textView = new TextView(context);
        textView.setText(String.valueOf(string.charAt(position)));
        return textView;
    }
}

Layout

In layout, we have GridView layout containing some attributes

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/gridView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="exceptionbound.com.gridviewinandroid.MainActivity"
    android:padding="30dp"
    android:numColumns="auto_fit"
    >
</GridView>

Comments

comments

Leave A Reply

Your email address will not be published.