GridView Android :
Gridview is similar to listview in Android but with more column . In listview we have rows, but in grid we have columns. if you are not aware with
gridview, youcan read Listview.
gridview, youcan read Listview.
Gridview allows user to scroll data till end. In layman we can say, multiple textview inside scrollview.
You have to define android:numColumns="2"
Gridview Android |
You have to define android:numColumns="2"
Lets have a look at code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.stacklearning.simlegridview.MainActivity">
<GridView
android:id="@+id/grid"
android:numColumns="2"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</GridView>
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.stacklearning.simlegridview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
GridView gridView;
List<String> gridValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.grid);
gridValue = new ArrayList<>();
gridValue.add("First Column Grid View");
gridValue.add("Second Column Grid View");
gridValue.add("Third Column Grid View");
gridValue.add("Forth Column Grid View");
gridValue.add("Fifth Column Grid View");
gridValue.add("Sixth Column Grid View");
gridValue.add("Seventh Column Grid View");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, gridValue);
gridView.setAdapter(adapter);
// GridView Item Click Listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int itemPosition = position;
String itemValue = (String) gridView.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
"Position clicked:" + itemPosition + " Grid Item is : " + itemValue, Toast.LENGTH_LONG)
.show();
}
});
}
}
_________________________________________________________________________
Most Searched Articles :
Constraint Layout in Android
MVP in Android
0 comments:
Post a Comment