How To Add A Textview To A Gridview In Android
I already know how to add String's to a gridView in android however I want to add textviews to format the text( Gravity, color, etc). This is my current code: GridView gridView = (
Solution 1:
try it with something like this
gridview.xml
<?xml version="1.0" encoding="utf-8"?><GridViewxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/gridView1"android:numColumns="auto_fit"android:gravity="center"android:columnWidth="100dp"android:stretchMode="columnWidth"android:layout_width="fill_parent"android:layout_height="fill_parent" ></GridView>
item.xml
<TextViewandroid:id="@+id/grid_item_label"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@+id/label"android:layout_marginTop="5px"android:textSize="15px" ></TextView>
Custom adapter class for textView
publicclassTextViewAdapterextendsBaseAdapter {
private Context context;
privatefinal String[] textViewValues;
publicTextViewAdapter(Context context, String[] textViewValues) {
this.context = context;
this.textViewValues = textViewValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflaterinflater= (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = newView(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.item, null);
// set value into textviewTextViewtextView= (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(textViewValues[position]);
} else {
gridView = (View) convertView;
}
return gridView;
}
@OverridepublicintgetCount() {
return textViewValues.length;
}
@Overridepublic Object getItem(int position) {
returnnull;
}
@OverridepubliclonggetItemId(int position) {
return0;
}
}
and then , finally set adapter in your main class
gridView.setAdapter(newTextViewAdapter(this, YOUR_ARRAY_WITH_TEXT_FOR_TEXTVIEWS));
also note that you can pass any other values like color of text and as another argument in constructor and then set them in adapter like ...
textView.setColor(textViewColors[position]);
for attributes that all textview have in common you can change the item.xml only :) i hope it helped you ....
Solution 2:
Simply do name.getText() and you're done!
Post a Comment for "How To Add A Textview To A Gridview In Android"