In drawable there is a simple shape:

<?xml version="1.0" encoding="utf-8"?> <shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="15dp"/> <solid android:color="#ffcd7821"/> </shape> 

It is the background for RelativeLayout:

 <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="wrap_content" tools:context=".MainActivity" android:background="@drawable/shape"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout> 

You need to programmatically change the color shape at the start of the action. I do it like this:

 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GradientDrawable gd = (GradientDrawable) getResources().getDrawable(R.drawable.shape); gd.setColor(Color.BLUE); } 

The color at the start of the activation does not change. But it changes when the restart is activated.

Questions:
Why does the color shape not change at the start ??
How to make the shape change color when you first start activating ??

    3 answers 3

    Use in the onStart () method:

     @Override protected void onStart() { super.onStart(); GradientDrawable gd = (GradientDrawable) getResources().getDrawable(R.drawable.shape); gd.setColor(Color.BLUE); } 

      It came to me.
      The thing is that when you first start, the setContentView(R.layout.activity_main); first received setContentView(R.layout.activity_main);
      with value
      solid android:color="#ffcd7821"
      and subsequent changes to the shape did not fall into it.

      You must first make changes to the shape, and then load the content.
      If you do this, then everything works:

       @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GradientDrawable gd = (GradientDrawable) getResources().getDrawable(R.drawable.shape); gd.setColor(Color.BLUE); setContentView(R.layout.activity_main); } 
      • Frankly, surprised. I did not think that the resources in xml can be edited in the process of the program. - ViR

      I did not understand what you want, but I see the android of the same opinion. Let me explain what you are doing: create a new object based on the xml of the resource and change the color in it. Why do you need to change the color if you do not apply this object further?

      As I understand it, you need to change the background color of the activity? Then simply call the setBackgraund method for the root view or by id for the specified RelativeLayout.

      Want to change the color in the resource itself? Alas, xml resources are not changeable from code.