Monday, October 22, 2012

Android Grid View


In java file
GirdView_Act.java


package GirdView.app;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class GirdView_Act extends Activity implements
AdapterView.OnItemSelectedListener {
TextView selection;
String[] items = { "one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "thirteen", "fouteen", "fifteen",
"sixteen", "seventeen", "eighteen", "ninteen", "twenty",
"twenty one", "twenty two", "twenty three", "twenty four",
"twenty five", "twenty six", "twenty seven", "twenty eight",
"twenty nine", "thirty", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten", "eleven", "thirteen",
"fouteen", "fifteen", "sixteen", "seventeen", "eighteen",
"ninteen", "twenty", "twenty one", "twenty two", "twenty three",
"twenty four", "twenty five", "twenty six", "twenty seven",
"twenty eight", "twenty nine", "thirty", };

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection = (TextView) findViewById(R.id.selection);
GridView g = (GridView) findViewById(R.id.grid);
g.setAdapter(new FunnyLookingAdapter(this,
android.R.layout.simple_list_item_1, items));
g.setOnItemSelectedListener(this);
}

public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
selection.setText(items[position]);
}

public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}

private class FunnyLookingAdapter extends ArrayAdapter {
Context ctxt;

@SuppressWarnings("unchecked")
FunnyLookingAdapter(Context ctxt, int resource, String[] items) {
super(ctxt, resource, items);
this.ctxt = ctxt;
}

public View getView(final int position, View convertView,
ViewGroup parent) {
TextView label = (TextView) convertView;
if (convertView == null) {
convertView = new TextView(ctxt);
label = (TextView) convertView;
}
label.setText(items[position]);
return (convertView);
}
}
}

In xml files
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<GridView
android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="35px"
android:horizontalSpacing="5px"
android:numColumns="auto_fit"
android:columnWidth="100px"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</LinearLayout>



No comments:

Post a Comment