I would like to ask how can I change the background color of an android app /provided that I have an array of colors/ Below I apply the code that I tried to write in order to do this task: The task is to change the background color of the app, based on the currently chosen color from the dropdown list(spinner). I would be very grateful if you could give me some hints on how can I fix this issue.
package com.example.assignment3_yoanivanov_322321010;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
LinearLayout linearLayout;
Spinner spinner;
String[] items = {"red","green","blue","orange","yellow","gray"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//textView = (TextView) findViewById(R.id.txtMsg);
spinner = (Spinner) findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, items);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String color = parent.getItemAtPosition(position).toString();
//Toast.makeText(parent.getContext(),color,Toast.LENGTH_LONG).show();
switch(color){
case "red":
linearLayout.setBackgroundColor(Color.RED);
case "green":
linearLayout.setBackgroundColor(Color.GREEN);
case "blue":
linearLayout.setBackgroundColor(Color.BLUE);
case "orange":
linearLayout.setBackgroundColor(Color.rgb(255, 165, 0));
case "yellow":
linearLayout.setBackgroundColor(Color.YELLOW);
case "GRAY":
linearLayout.setBackgroundColor(Color.GRAY);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
