通过编程创建的网格视图内容的文本颜色 [英] Text color by programmatically created grid view content

查看:110
本文介绍了通过编程创建的网格视图内容的文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解如何在设计视图中执行此操作,但是我不确定如何基于以编程方式创建的元素来创建样式.我遵循了教程,这是我的位置:

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.

如何设置添加到gridView的项目的文本颜色?

How would I set the text color of the items added to the gridView?

推荐答案

2个解决方案:动态或具有自定义布局.

2 solutions: dynamically or with a custom layout.

  • 动态:当您在ArrayAdapter中覆盖getView()方法时,可以使用setTextColor(...)设置文本颜色,如下所示:

  • 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.

    这篇关于通过编程创建的网格视图内容的文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆