Android Spinner, Bundle and Toast Example

来源:互联网 时间:1970-01-01

Today we will learn about Android Spinner , Bundle and Toast . This tutorial will give you a hands on experience in using Android Spinner as a drop-down menu, passing data using android bundle and showing popup notification using android toast .

We will create an android app that consists of a simple spinner which allows to select an item from a drop down menu. We will display static data in spinner and after selecting an item from spinner a toast message will be shown. To pass data in the form of bundles between activities, we’ll use a button to perform an intent and display the data passed in the next screen.

What is Android Spinner?

Android Spinner is nothing but the dropdown list seen in other programming languages such as in HTML pages.

In Android, Spinner is used to select one value from a set of values. In the default state, a spinner shows its currently selected value. Touching the spinner displays a dropdown menu with all other available values, from which the user can select a new one. Android spinner is associated with AdapterView . So we need to use one of the adapter classes with spinner.

Following xml file shows the layout of a typical spinner in android which consists of a text label and a spinner element tag.

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:padding="10dip"android:layout_width="fill_parent"android:layout_height="wrap_content"><!-- Text Label --><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="10dip"android:text="Category:"android:layout_marginBottom="5dp"/><!-- Spinner Element --><Spinner android:id="@+id/spinner"android:layout_width="fill_parent"android:layout_height="wrap_content"android:prompt="@string/spinner_title"/></LinearLayout>

Following snippet shows how to use a spinner in the activity class.

Spinner spinner = (Spinner) findViewById(R.id.spinner); What is Android Bundle?

Android Bundle is generally used for passing data between various activities of android. It depends on you what type of values you want to pass, but bundle can hold all types of values, and pass to the next activity.

Following snippet shows how to bring bundles in the frame.

Intent intent = new Intent(MainActivity.this,SecondActivity.class);intent.putExtra("Key","value"); startActivity(intent);

To get the passed values in the SecondActivity we use the following snippet.

Bundle extras = intent.getExtras(); String tmp = extras.getString("Key"); What is Android Toast?

Android Toast is used to show notification for a particular interval of time. After sometime it disappears. It doesn’t block the user interaction and you can’t close it like alerts. The android.widget.Toast class is the subclass of java.lang.Object class.

Constants used in Android Toast public static final int LENGTH_LONG:displays view for the long duration of time public static final int LENGTH_SHORT: displays view for short duration of time Android Toast Methods public static Toast makeText(Context context, CharSequence text, int duration): makes the toast containing text and duration public void show(): displays toast public void setMargin (float horizontalMargin, float verticalMargin): changes the horizontal and vertical margin difference

Following are some basic usages of Toasts.

Toast.makeText(getApplicationContext(),"Default Toast",Toast.LENGTH_SHORT).show(); Toast toast=Toast.makeText(getApplicationContext(),"Setting Margins",Toast.LENGTH_SHORT); toast.setMargin(50,50); toast.show();

So lets jump onto the practical part where we merge these three components to represent a meaningful app.

Project Structure

Let’s start with the layout of the MainActivity class. We just need to add Button to the basic_spinner.xml file.

<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" android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"><LinearLayoutandroid:orientation="vertical"android:padding="10dip"android:id="@+id/linear_layout"android:layout_width="fill_parent"android:layout_height="wrap_content"><!-- Text Label --><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="10dip"android:text="Category:"android:layout_marginBottom="5dp"/><!-- Spinner Element --><Spinnerandroid:id="@+id/spinner"android:layout_width="fill_parent"android:layout_height="wrap_content"android:prompt="@string/spinner_title"/></LinearLayout><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="NEXT"android:id="@+id/button"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"android:layout_marginBottom="137dp" /></RelativeLayout>

The layout of the SecondActivity is as follows:

<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" android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textAppearance="?android:attr/textAppearanceMedium"android:text="Empty"android:id="@+id/txt_bundle"android:layout_alignParentTop="true"android:layout_centerHorizontal="true"android:layout_marginTop="103dp" /></RelativeLayout>

Here is the android manifest file.

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="journaldev.com.spinners" ><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name=".MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity><activity android:name=".SecondActivity"/></application></manifest>

The MainActivity and SecondActivity java classes are defined as follows:

package journaldev.com.spinners;import android.app.Activity;import android.content.Intent;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.Spinner;import android.widget.Toast;import java.util.ArrayList;import java.util.List;public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener { @Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// Spinner elementfinal Spinner spinner = (Spinner) findViewById(R.id.spinner);Button button=(Button)findViewById(R.id.button);// Spinner click listenerspinner.setOnItemSelectedListener(this);// Spinner Drop down elementsList<String> categories = new ArrayList<String>();categories.add("Item 1");categories.add("Item 2");categories.add("Item 3");categories.add("Item 4");categories.add("Item 5");categories.add("Item 6");// Creating adapter for spinnerArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);// Drop down layout style - list view with radio buttondataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);// attaching data adapter to spinnerspinner.setAdapter(dataAdapter);button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {Intent intent= new Intent(MainActivity.this,SecondActivity.class);intent.putExtra("data",String.valueOf(spinner.getSelectedItem()));startActivity(intent); }}); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {// On selecting a spinner itemString item = parent.getItemAtPosition(position).toString();// Showing selected spinner itemToast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show(); } public void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub }} package journaldev.com.spinners;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class SecondActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.second_activity);TextView textView=(TextView) findViewById(R.id.txt_bundle);Bundle bundle=getIntent().getExtras();String data=bundle.get("data").toString();textView.setText(data); }}

In short, we display a toast when an item from the spinner dropdown menu is selected. On button click we pass the selected spinner item as a string value to the next activity using android bundle. Then data is retrieved from the bundle and displayed in a textview. Quick easy and simple isn’t it?

The screenshots of the app are shown below. I am running it on one of the emulator.

First screen showing drop down list contents when clicked on spinner.

After an item is selected, toast notification message appears for some time.

After sometime toast notification disappears as shown in below image. It doesn’t stop us in clicking the next button.

Finally in second screen, selected item from the drop down list is shown. The data flow from first screen to second one is achieved using android bundle.

That’s all for now, we will look into more android features and example projects in coming posts. You can download Android Spinner, Bundle and Toast example project from below link.

Download Android Spinner, Bundle and Toast Example Project 0 downloads

相关阅读:
Top