GridView in Android
GridView in android shows the items in two dimensional scrolling grid . For details see the GridView reference.
Step 1: Create Project
a) Open Android Studio
b) Go to File >New> New Project > Project Name > Next > Next > Next > Finish
Step 2 : Layout Design
open activity_main.xml file and add the bellow code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="50dp"
android:stretchMode="columnWidth">
</GridView>
</RelativeLayout>
Step 3 : Code
open MainActivity class and add the bellow code
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends Activity {
GridView gridView;
ArrayList<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridview);
// initialize ArrayList and add value in list
list = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
if(i<=9){
list.add("0"+i);
}else {
list.add(""+i);
}
}
// adapter for showing the data in GridView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
// set the adapter in GridView
gridView.setAdapter(adapter);
// get the selected item from GridView
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getApplicationContext(),
list.get(position), Toast.LENGTH_SHORT).show();
}
});
}
}
Step 4 : Output
Find Us :
Facebook : @apnaandroid
Google+ : Apna Java
Youtube : Android & Java Tutorial
Comments
Post a Comment