Как изменить цвет текста listview

In Android a ListView is a UI element used to display the list of items. This list is vertically scrollable and each item in the ListView is operable. A ListView adapter is used to supply items from the main code to the ListView in real time. By default the TextView font

In Android, a ListView is a UI element used to display the list of items. This list is vertically scrollable and each item in the ListView is operable. A ListView adapter is used to supply items from the main code to the ListView in real-time. By default, the TextView font size is 14 sp and color is “@android:color/tab_indicator_text”.

ListView  in Android

In this article, we will show you how you could change the ListView text color in Android. Follow the below steps once the IDE is ready.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We have implemented a ListView in the main layout file.

XML

Step 3: Working with the list_item.xml file

Below is the code for the Item layout for displaying the item in the ListView. We have added textColor and textSize attributes to the TextView to change the text color and size.

XML

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/text_view"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textColor="@android:color/holo_orange_dark"

        android:textSize="30sp"

        android:textStyle="bold" />

</RelativeLayout>

Step 4: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. In the main code, we have primarily declared an array and supplied the array items to the ListView with the help of an adapter.

Kotlin

package org.geeksforgeeks.changelistviewtextcolor

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.ArrayAdapter

import android.widget.ListView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        val mItems: Array<String> = arrayOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Zero")

          val mListView = findViewById<ListView>(R.id.list_view)

          val mAdapter = ArrayAdapter<String>(this, R.layout.list_item, R.id.text_view, mItems)

          mListView.adapter = mAdapter

    }

}

Output:

You can see that the text color and size have changed in the ListView.

Output

Change ListView Item Text Color

ListView shows a list of items in an Android application user interface. ListView shows multiple items at a time. This is a vertically scrollable widget. Items are positioned sequentially. One immediately below another item. By default, the ListView widget is looking good and standard. But sometimes, android app developers want to change the default font/text color of ListView element items.

This android app development tutorial will demonstrate and describe to you how can we change the ListView item’s text color. But there has no direct way or a single attribute or a single method to change the ListView item text color. So we have to write a few lines of code to get the result.

In the first step, we add a ListView widget to our XML layout file. Next, in the java file, we do our sequence of jobs to apply a specific color to ListView items. ListView items are populated from an array adapter. And an array adapter builds using an array list and an array list gets elements from an array.

The actual code we write while we initialize the ArrayAdapter. Here we override the ArrayAdapter getView method and cast the view instance as a TextView widget. Now, we set the text color for the TextView widget. This is the color that will show in our ListView widget’s item text color. This TextView act as a single item of the ListView element. So, finally, we will get our desired ListView with the specified text color.

MainActivity.java


package com.cfsuman.androidtutorials;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        ListView listView = findViewById(R.id.listView);


        // Initializing a new String Array
        String[] fruits = new String[] {
                "African mango",
                "Ambarella",
                "American Black Elderberry",
                "Ackee",
                "American persimmon",
                "Babaco"
        };


        // Create a List from String Array elements
        List<String> fruits_list = new ArrayList<String>
                (Arrays.asList(fruits));


        // Create an ArrayAdapter from List
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
                (
                        this,
                        android.R.layout.simple_list_item_1,
                        fruits_list
                ){
            @Override
            public View getView(
                    int position, View convertView, ViewGroup parent){
                // Get the Item from ListView
                View view = super.getView(position, convertView, parent);

                // Initialize a TextView for ListView each Item
                TextView textView = (TextView) view
                        .findViewById(android.R.id.text1);

                // Set the text color of TextView (ListView Item)
                textView.setTextColor(Color.parseColor("#5218FA"));

                // Generate ListView Item using TextView
                return view;
            }
        };

        // DataBind ListView with items from ArrayAdapter
        listView.setAdapter(arrayAdapter);
    }
}

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="24dp">

    <ListView
        android:id="@+id/listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Change ListView Text Color in Android

Not happy with the default layout of items in a ListView. It is straightforward to provide your own layout to change the ListView item’s visual formatting, such as text color, or font size, background color, etc. To change ListView text color in Android a custom layout is used for the list items. (Instead of using one of Android’s default layouts.) This custom layout can be modified to change the font attributes of the list items, color, bold, size, etc.

Android Logo

(This change text color in ListView tutorial assumes that Android Studio is installed, a basic App can be created and run, and the code in this article can be correctly copied into Android Studio. Adapt the data and code to meet your own requirements. When entering code in Studio add import statements when prompted by pressing Alt-Enter. In this article Amercian color spelling is used and not UK colour in line with the Android SDK)

How to Set Text Color in Android ListView

This Android ListView tutorial assumes that you have a simple one line per entry text list up and running in an Android App. If not see the Tek Eye article Add a Simple List to an App.

Open the App project in Android Studio. Add a new layout file to the project using the Project explorer. To do this use the File menu or context menu (normally right-click) on app in the Project explorer. Select New then XML and Layout XML File. Set the Layout File Name, here
called listrow, leave the Root Tag at LinearLayout and Target Source Set unchanged at main. Click Finish and listrow.xml will be created in the res/layout folder.

With listrow.xml open in the Design window use the Palette to drop a Plain TextView from the Widgets list onto the new layout. Now change some of the layout and TextView Properties. Highlight the layout (click a blank area of the device screen shown in the Design window or click LinearLayout in the Component Tree) and change layout:width and layout:height to wrap_content. Select the TextView and change the required font (text) Properties, e.g. set textSize to 20sp (scaled pixels) and textColor to #ff0000 to change the ListView text color to red. If you click on the Text tab the XML should be similar to this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView2"
        android:textSize="20sp"
        android:textColor="#ff0000" />
</LinearLayout>

In the following line of code an ArrayAdapter is created to link a ListView declared as coffeeList to a string array called coffeeChoices. The ArrayAdapter is given the layout listrow and the textView2 id:

coffeeList.setAdapter(new ArrayAdapter<String>(this, R.layout.listrow, R.id.textView2, coffeeChoices));

Run the App to try out the ListView font changes.

Red Text ListView

Play with the other layout and TextView properties to see the effect they have. E.g. open textStyle under the Properties list and check bold and italic. The code is available in redlist.zip for download with an instructions.txt on how to import the project into Studio.

See Also

  • If a Rendering Problems message is displayed when viewing layouts see the article Android Studio Rendering Problems.
  • See the other Android examples on Tek Eye.

Author:  Published:2016-04-18  Updated:2016-05-29  

В Android ListView — это элемент пользовательского интерфейса, используемый для отображения списка элементов. Этот список можно прокручивать по вертикали, и каждый элемент в ListView можно использовать. Адаптер ListView используется для передачи элементов из основного кода в ListView в режиме реального времени. По умолчанию размер шрифта TextView равен 14 sp, а цвет — «@android:color/tab_indicator_text».

В этой статье мы покажем вам, как вы можете изменить цвет текста ListView в Android. После того как среда IDE будет готова, выполните следующие шаги.

Пошаговая реализация

Шаг 1. Создайте новый проект в Android Studio.

Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio». Мы продемонстрировали приложение на Kotlin, поэтому убедитесь, что вы выбрали Kotlin в качестве основного языка при создании нового проекта.

Шаг 2: Работа с файлом activity_main.xml

Перейдите к приложению > res > layout > activity_main.xml и добавьте приведенный ниже код в этот файл. Ниже приведен код файла activity_main.xml . Мы внедрили ListView в основной файл макета.

XML

Шаг 3: Работа с файлом list_item.xml

Ниже приведен код макета элемента для отображения элемента в ListView. Мы добавили атрибуты textColor и textSize в TextView, чтобы изменить цвет и размер текста.

XML

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/text_view"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textColor="@android:color/holo_orange_dark"

        android:textSize="30sp"

        android:textStyle="bold" />

</RelativeLayout>

Шаг 4: Работа с файлом MainActivity.kt

Перейдите к файлу MainActivity.kt и обратитесь к следующему коду. Ниже приведен код файла MainActivity.kt . Комментарии добавляются внутри кода, чтобы понять код более подробно. В основном коде мы в первую очередь объявили массив и предоставили элементы массива в ListView с помощью адаптера.

Kotlin

package org.geeksforgeeks.changelistviewtextcolor

import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.widget.ArrayAdapter

import android.widget.ListView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        val mItems: Array<String> = arrayOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Zero")

          val mListView = findViewById<ListView>(R.id.list_view)

          val mAdapter = ArrayAdapter<String>(this, R.layout.list_item, R.id.text_view, mItems)

          mListView.adapter = mAdapter

    }

}

Выход:

Вы можете видеть, что цвет и размер текста изменились в ListView.

РЕКОМЕНДУЕМЫЕ СТАТЬИ

How to create and modify ListView with different item value text color using #color code.

In this tutorial we are modifying all the items text color in list view with the use of setting up current view as textview and after that change the listview text color. So here is the complete step by step tutorial for Change listview Item text color android programmatically.

android-project-download-code-button

How to Change listview Item text color android programmatically.

Code for MainActivity.java file.

 package com.changelistviewitemtextcolor_android_examples.com;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.view.ViewGroup;

public class MainActivity extends Activity {
 
 ListView listView;
 String[] listValue = new String[] 
 {
 "ONE",
 "TWO",
 "THREE",
 "FOUR",
 "FIVE",
 "SIX"
 };
 
 List<String> LISTSTRING;
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 listView = (ListView)findViewById(R.id.listView1);
 
 LISTSTRING = new ArrayList<String>(Arrays.asList(listValue));
 
 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_2, android.R.id.text1, LISTSTRING){
 
 @Override
 public View getView(int position, View convertView, ViewGroup parent){
 
 View view = super.getView(position, convertView, parent);

 TextView ListItemShow = (TextView) view.findViewById(android.R.id.text1);

 ListItemShow.setTextColor(Color.parseColor("#fe00fb"));

 return view;
 }
 
 };
 
 listView.setAdapter(adapter); 
 
 
 
 }
 }

Code for activity_main.xml layout file.

 <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:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.changelistviewitemtextcolor_android_examples.com.MainActivity" >

 <ListView
 android:id="@+id/listView1"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true" >
 </ListView>

</RelativeLayout>

Screenshot:

Change listview Item text color android programmatically

Click here to download Change listview Item text color android programmatically project with source code.

This example demonstrates how to change the color and font of Android ListView using Kotlin.

Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Example

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">
<TextView
   android:id="@+id/textView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:fontFamily="sans-serif-condensed"
   android:textColor="@android:color/holo_orange_dark"
   android:textSize="24sp"
   android:textStyle="italic|bold" />
</LinearLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   var operatingSystem: Array<String> = arrayOf("Android", "IPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X")
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val listView: ListView = findViewById(R.id.listView)
      val adapter = object : ArrayAdapter<String>(this, R.layout.list_item, R.id.textView, operatingSystem) {
      }
      listView.adapter = adapter
   }
}

Step 4 − Create a Layout resource file (list_item.xml) and add the following code −

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">
<TextView
   android:id="@+id/textView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:fontFamily="sans-serif-condensed"
   android:textColor="@android:color/holo_orange_dark"
   android:textSize="24sp"
   android:textStyle="italic|bold" />
</LinearLayout>

Step 5 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Click here to download the project code.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить цвет текста coreldraw
  • Как изменить цвет текста adobe premiere pro
  • Как изменить цвет тегов
  • Как изменить цвет татуажа губ
  • Как изменить цвет таблицы wordpress

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии