How to change the Text Color of a listview?

Asked

Viewed 9,331 times

0

I’m trying to change the color of the text of this listview that I did by following some examples on the internet, but the most I could was the comment from row 39* txt.setTextColor(Color.GREEN); The problem is that this only changes the color when clicked and still the color does not return to normal. : / I need a solution to make the appearance a little more beautiful, I’ve tried several tutorials from other site but they did not work very well.

I would like a solution that is as simple as possible for studies. But anything that works is also worth. :)

The Main class:

public class Main extends Activity {
    public ListView list;
    static int numPerildo = 2;
    static String perildoAtual;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Cursos);

        list = (ListView) findViewById(R.id.list);
        list.setAdapter(adapter);

        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View view, int position, long id) {

                TextView txt = (TextView) view;     //funciona
                //txt.setTextColor(Color.GREEN);
                //TextView txt = (TextView) view.findViewById(R.id.post);

                //mensagem.setTitle("Escolha qual o perildo");
                //mensagem.setMessage( txt.getText().toString() );
                //mensagem.setNeutralButton("OK", null);
                //txt.setTextColor(color.white);

                //trace("Item selecionado : " + position);

                if(txt.getText().toString().equals("valor 1")){
                    numPerildo = 5;
                    telaPerildo();
                }

                perildoAtual = txt.getText().toString();
            }
        });

    }

    public void telaPerildo(){
        Intent i = new Intent(this, Periodo.class);
        startActivity(i);
    }

    static final String[] Cursos = new String[] {"valor 1", 
        "valor 2", 
        "valor 3"};


    public void toast (String msg){
        Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_SHORT).show ();
    } 

    private void trace (String msg){
        toast (msg);
    }

}

A Main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/azulClaro"
    tools:context="${packageName}.${activityClass}" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Escolha o seu curso:"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/text" >

    </ListView>

</RelativeLayout>

2 answers

5


From what I understand, you want to change the color of all the items in the ListView.

How are you using the android.R.layout.simple_list_item_1, which is provided by Android and is using a ArrayAdapter, cannot change color with this setting.

Change the color of text in the method onItemClick of OnItemClickListener in fact will only change during click and will not return to normal.

There are two options:

Use a custom layout, similar to simple_list_item_1 with the modification in TextView, as well as below:

xml item.

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:textColor="@color/suaCor"
/>

We must respect the id which is attributed to the TextView so that the ArrayAdapter know how to locate the TextView.

And use in your Activity thus:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.item, Cursos);

    list = (ListView) findViewById(R.id.list);
    list.setAdapter(adapter);

    // Restante do código...
}

The second option is to extend the ArrayAdapter to change the color when instilling the item. Thus:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, Cursos) {

        @Override
        public View getView (int position, View convertView, ViewGroup parent) {

            View view = super.getView(position, convertView, parent);

            // Como o simple_list_item_1 retorna um TextView, esse cast pode ser feito sem problemas
            ((TextView) view).setTextColor(suaCor);

            return view;
        }

    };

    list = (ListView) findViewById(R.id.list);
    list.setAdapter(adapter);

    // Restante do código...
}

The two alternatives are possible, the first one is more "correct", because you change directly the layout of the item and also the more possibilities of customization and is more performative than the second.

The second one is a bit forced (using anonymous classes), because it overloads the behavior of the Adapter, gives to do a lot of this way in terms of visibility logic and etc (you can create your own class that extends Arrayadapter in a separate file, it is more organized).

In short, for this simple case I recommend the first hehe

  • Huumm, now yes it’s making sense, thank you so much @Wakim ! I prefer the second option and it worked perfectly, you know what I mean!

  • I’ve made some considerations to help.

  • 1

    Dannark follows @Walkim’s considerations (1st option) that sooner or later you will need to create your own adapter, so you can use your objects in the adapter. Take advantage of the features of Java and Android XML objects.

  • Thanks a lot :)

3

You have to create a layout costumed par to ListView, and then use that layout on the adapter.

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/lisItem"
        android:textColor="@color/green"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
  • Can you show me how to do that? Thanks for the quick reply!

  • 1

    See the @Walkim response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.