I understand how to do this in design view, but I'm not sure how to create a style based on programmatically created elements. I followed a tutorial and here's where I'm at:
I have a grid view which is populated by a string array as in the code below:
...
gridView = (GridView) findViewById(R.id.gridView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strData);
gridView.setAdapter(adapter);
Each element of the string array populates the grid just fine.
How would I set the text color of the items added to the gridView?
2 solutions: dynamically or with a custom layout.
Dynamically: you can set a text color by using setTextColor(...)
when you Override the getView()
method in your ArrayAdapter, something like this:
gridview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strData) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text = (TextView) view.findViewById(android.R.id.text1);
text.setTextColor(getResources().getColor(R.color.my_color));
return view;
}
});
Custom Layout: this is the simplest way, build a custom layout as:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:textColor="@color/my_color"
android:background="@drawable/my_background"
android:padding="5sp"
android:singleLine="true"
android:gravity="center" />
Then, set it to your adapter:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_layout_above, strData);
Even if, you wanted this dynamically, I'm not sure but I think it's better to do with a custom layout.
Hope this helps.
By creating a custom layout and supplying it to your ArrayAdapter
. Currently you are supplying the default layout android.R.layout.simple_list_item_1
. Create a new layout xml like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/flFragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
And style it however you want.
You can use it like this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.custom_layout, R.id.tvText, strData);