user7197369
user7197369

Reputation:

Android change text color automatically programmatically

I need help in changing text color programmatically in Android by 1-sec interval. The color should be

Upvotes: 2

Views: 4793

Answers (2)

Shadman Adman
Shadman Adman

Reputation: 431

first create an array of color in xml file.

<array name="textViewColors">
    <item>@color/bright_pink</item>
    <item>@color/red</item>
    <item>@color/orange</item>
    <item>@color/yellow</item>
    <item>@color/chartreuse</item>
    <item>@color/green</item>
    <item>@color/spring_green</item>
    <item>@color/cyan</item>
    <item>@color/azure</item>
    <item>@color/blue</item>
    <item>@color/violet</item>
    <item>@color/magenta</item>
</array>

and create a thread :

    TextView textView;
//an array to access the color we declare in xml file
     int[] textViewColors = context.getResources().getIntArray(R.array.textViewColors); 
     Thread changeColor = new Thread() {
            @Override
            public void run() {
                try {
                    sleep(5000); //time that set interval. this is for 5 sec
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            for(int i=0;i<=textViewColors.size();i++){
                            textView.setTextColor(textViewColors[i]);

                        }
                        }
                    });

                } catch (Exception e) {

                }
            }
        };

and excute thread wherever you want. for example in onCreate:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
   ---> changeColor.start();
    }

I hope it is be useful to you.

Upvotes: 0

Jasurbek
Jasurbek

Reputation: 2966

You can try this

In Kotlin

val handler = Handler()
val colors = arrayOf(Color.BLUE, Color.WHITE, Color.YELLOW, Color.GREEN)
var i;
val runnable = Runnable {
    i = i % colors.size
    yourView.setTextColor(colors[i])
    i++
    handler.postDelayed(this, 1000) 
}
handler.postDelayed(runnable, 1000)

or in Java

 Handler handler = new Handler();
        int[] colors = {Color.BLUE, Color.WHITE, Color.YELLOW, Color.GREEN};
        int i;
 Runnable runnable = new Runnable () {
        @Override
        public void run() {
             i = i % colors.length;
             yourView.setTextColor(colors[i]);
             i++;
             handler.postDelayed(this, 1000);
         }                
      }
handler.postDelayed(runnable, 1000);

Upvotes: 4

Related Questions