Android Spinner –下拉列表

本文提供了一个使用Android Spinner创建下拉菜单的实践教程。通过Spinner,可以实现从列表中选择项目并使用bundle在活动间传递数据,同时展示Toast通知。教程包括Spinner布局、适配器设置、数据传递和Toast显示的详细步骤。
摘要由CSDN通过智能技术生成

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.

本教程将为您提供使用Android Spinner作为下拉菜单,使用android bundle传递数据以及使用android toast显示弹出通知的实践经验。

We will create an android application that consists of a simple spinner that allows selecting an item from a drop down list. We will display static data in the spinner. Selecting an item from spinner would display a toast message.

我们将创建一个包含一个简单微调器的android应用程序,该微调器允许从下拉列表中选择一个项目。 我们将在微调器中显示静态数据。 从微调器中选择一个项目将显示一条祝酒消息

To pass data in the form of bundles between activities, we’ll use a button to perform an intent and display the data passed to the next screen.

为了在活动之间以束的形式传递数据,我们将使用按钮执行意图并显示传递到下一个屏幕的数据。

Android微调器 (Android Spinner)

Android Spinner is just a drop down list similar to what’s seen in other programming languages such as in HTML pages.

Android Spinner只是一个下拉列表,类似于在其他编程语言(例如HTML页面)中看到的内容。

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 drop down menu with all other available values, from which the user can select a new one.

在Android中,Spinner用于从一组值中选择一个值。 在默认状态下,微调器显示其当前选定的值。 触摸微调器将显示一个具有所有其他可用值的下拉菜单,用户可以从中选择一个新的值。

Android spinner is associated with AdapterView. So we need to set the adapter class with the Spinner.

Android微调器与AdapterView关联。 因此,我们需要使用Spinner设置适配器类。

Android下拉列表 (Android Drop Down List)

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

以下xml文件显示了android中典型的微调框的布局,该布局由文本标签和微调框元素标签组成。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    
    <!-- Text Label -->
    <TextView
        android: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);

Let’s develop an application where we pass the selected value from the Spinner onto the next screen using Bundles and display a Toast message of the selected value at the same time.

让我们开发一个应用程序,在该应用程序中,我们使用Bundles将微调器中的选定值传递到下一个屏幕,并同时显示选定值的Toast消息。

Android Spinner示例项目结构 (Android Spinner Example Project Structure)

Below image shows the android studio project for spinner example.

下图显示了微调器示例的android studio项目。

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

让我们从MainActivity类的布局开始。 我们只需要将Button添加到basic_spinner.xml文件中。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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">


    <LinearLayout
        android:orientation="vertical"
        android:padding="10dip"
        android:id="@+id/linear_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <!-- Text Label -->
        <TextView
            android: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>

    <Button
        android: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:

SecondActivity的布局如下:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://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">


    <TextView
        android: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.

这是Android Manifest文件。

AndroidManifest.xml

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="journaldev.com.spinners" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android: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.

MainActivitySecondActivity Java类的定义如下。

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 element
        final Spinner spinner = (Spinner) findViewById(R.id.spinner);
        Button button=(Button)findViewById(R.id.button);

        // Spinner click listener
        spinner.setOnItemSelectedListener(this);

        // Spinner Drop down elements
        List<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 spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner.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 item
        String item = parent.getItemAtPosition(position).toString();

        // Showing selected spinner item
        Toast.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 the above code, we’ve displayed 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 the data is retrieved from the bundle and displayed in a TextView. Quick easy and simple, isn’t it?

在上面的代码中,当从微调器下拉菜单中选择一个项目时,我们已经显示了一个祝酒词。 在单击按钮时,我们使用android bundle将选定的微调项作为字符串值传递给下一个活动。 然后,从包中检索数据并显示在TextView中。 快速简便,不是吗?

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

该应用程序的屏幕截图如下所示。 我正在其中一个仿真器上运行它。

The first screen shows the drop down list contents when the Spinner is opened.

打开微调框时,第一个屏幕显示下拉列表的内容。

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

选择一个项目后,Toast通知消息出现一段时间。

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

一段时间后,烤面包通知消失,如下图所示。 这并不能阻止我们单击下一步。

Finally, in the second screen, the selected item from the dropdown list is retrieved using Bundles and displayed in the TextView.

最后,在第二个屏幕中,使用Bundles检索下拉列表中的选定项目并显示在TextView中。

Below is a sample run of our android spinner example application in emulator.

以下是在模拟器中运行我们的Android Spinner示例应用程序的示例运行。

That’s all for now, we will look into Android ListView in next post. You can download Android Spinner, Bundle and Toast example project from below link.

到此为止,我们将在下一篇文章中研究Android ListView 。 您可以从下面的链接下载Android Spinner,Bundle和Toast示例项目。

Reference: Official Doc

参考: 官方文件

翻译自: https://www.journaldev.com/9231/android-spinner-drop-down-list

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值