Frezoki
Frezoki

Reputation: 47

How to change the background color with a button?

How do I change the color of the background randomly with a button press in Android studio?

Here is my code:

public class partymodus extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_partymodus);

    final TextView aufgabe=(TextView)findViewById(R.id.txt_aufgabe);
    final Button next =  (Button)findViewById(R.id.btn_next);

    next.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
            String[] aufgaben = getResources().getStringArray(R.array.name);
            Random rand = new Random();
            int n = rand.nextInt(aufgaben.length - 0) + 0;
            aufgabe.setText(aufgaben[n]);

        }
    });
}

Upvotes: 0

Views: 129

Answers (4)

Android Geek
Android Geek

Reputation: 9225

add view_name.setBackgroundColor(getResources().getColor(R.color.colorAccent)); line to set background color

this is my code:

   mButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mHomeLl.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        }
    });

Upvotes: 0

Naci Başak
Naci Başak

Reputation: 71

MyActivity.setOnClickListener(new View.OnClickListener()       {

@Override
public void onClick(View v) {

MyActivity.setBackgroundColor(getResources().getColor(R.color.RED));
}

Upvotes: 0

Othmane
Othmane

Reputation: 21

You have to add an ActionListener to your button and override the method:

public void actionPerformed(ActionEvent e) { 
    ...//code that reacts to the action... 
}

And sorry for my english i'm beginner

Upvotes: 2

Hancheng Dai
Hancheng Dai

Reputation: 1

As an un-profession to answer your question, you have to digging out what is jave graphic design pattern is before goes in official API, Here is a link to search the JFrame or Java.awt.Graphic, [1]

it't where you start to build the components on the graphic,since you are building with a button component, I may suggest you looking the Inherit or father interface of JFrame, and another Containers

Upvotes: 0

Related Questions