Create spinner with strings from the resource folder (res >> value folder). On changing spinner value, change image.
Software-required: Android Studio
Pre-requisite:
Basic knowledge of Android Studio.
Theory/Logic:
-
- Spinner is used to select one item from menu.
- It is like Drop Down Menu.
- I have added items in spinner by string.xml.
Program/Solution: -
- Activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<Spinner
android:layout_width="wrap_content"
android:id="@+id/spinner1"
android:layout_height="wrap_content"
android:entries="@array/img"
android:layout_marginTop="50dp"
android:layout_marginLeft="100dp"
/>
<ImageView android:src="@drawable/icon"
android:id="@+id/imageView1"
android:layout_height="wrap_content"
android:layout_weight="-5"
android:layout_width="match_parent"
/>
</LinearLayout>
- MainActivity.xml file:
package com.example./*Your Package Name*/;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.Spinner;
public class MainActivity extends Activity implements
OnItemSelectedListener {
/** Called when the activity is first created. */
Spinner sp;
ImageView img;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp=(Spinner)findViewById(R.id.spinner1);
sp.setOnItemSelectedListener(this);
img=(ImageView)findViewById(R.id.imageView1);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if(arg2==0)
{
img.setImageResource(R.drawable.img1);
}
if(arg2==1)
{
img.setImageResource(R.drawable.img2);
}
if(arg2==2)
{
img.setImageResource(R.drawable.img3);
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
- strings.xml file:
<resources>
<string name="app_name">Practical8</string>
<string name="hello">Hello World, Tut_2_1Activity!</string>
<string-array name="img">
<item>Labrador Retriever</item>
<item>Bulldog</item>
<item>Siberian Husky</item>
</string-array>
</resources>
Create spinner with strings from the resource folder (res >> value folder). On changing spinner value, change image.
Reviewed by Diploma Hub
on
February 02, 2022
Rating:
No comments: