Zhisong Ge
Zhisong Ge

Reputation: 11

Change the background color of Fragment in code

How to change the background color of a fragment in android programmatically instead of xml.

Upvotes: 1

Views: 7371

Answers (2)

safwan shaib
safwan shaib

Reputation: 13

Step1: In your xml of the fragment you want to change its background color, define the layout you're using with an id value such as:

 <androidx.constraintlayout.widget.ConstraintLayout
 android:id="@+id/fragment_layout">

Step2: Make an object of the layout type your're using and change the background color such as:

final ConstraintLayout constraintlayout;
constraintlayout=view.findViewById(R.id.fragment_layout);
constraintlayout.setBackgroundResource(R.color.maroon);

Note1: it can be any layout, i'm using a ConstraintLayout in this example.

Note2: maroon is a color I defined in clolrs.xml, use yoru own or you can import the Color class instead and use it such as (Color.BLACK).

Upvotes: 0

rafaelc
rafaelc

Reputation: 59264

Just do in your code:

fragment.getView().setBackgroundColor(Color.RED);

being fragment you Fragment object, and the argument the color you want. You can also parse colors using Color.parseColor(string) method (e.g Color.parseColor("#RRGGBB")).

Upvotes: 4

Related Questions