Create spinner with strings taken from resource folder(res >> value folder). On changing spinner value, change background of screen.
first create resource file, right click on values directory>New>Values Resource file and name it array, and your array.xml file will created on values folder. Now add following code in array.xml
array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="S">
<item>RED</item>
<item>BLUE</item>
<item>GREEN</item>
<item>YELLOW</item>
</string-array>
</resources>
activity_main.xml
<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="match_parent"
tools:context=".MainActivity"
android:id="@+id/rlVar1"
>
<Spinner
android:layout_centerInParent="true"
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/S"
/>
</RelativeLayout>
MainActivity.java
package com.example.helloworld;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = findViewById(R.id.spinner1);
RelativeLayout rl = findViewById(R.id.rlVar1);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_SHORT).show();
try {
rl.setBackgroundColor(Color.parseColor(adapterView.getItemAtPosition(i).toString()));
}catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
Output
0 Comments
Post a Comment