自学内容网 自学内容网

移动开发:下拉列表框实例

一、创建模块DoubanEntertainment

二、编写代码及配置内容

1.图片素材命名为xila.jpg

2.编写activity_main.xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/xila"
    android:orientation="horizontal"
    tools:context=".MainActivity">
    <Spinner
        android:id="@+id/spinner"
        android:entries="@array/ctype"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </Spinner>


    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="搜索"
        android:textColor="#F8F8FF"/>

</LinearLayout>
3.MainActivity.java代码
package com.example.doubanentertainment;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
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 = (Spinner) findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = parent.getItemAtPosition(position).toString();
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}
4.修改AndroidManifest.xml的主题样式

5.新建array.xml代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="ctype">
        <item>全部</item>
        <item>电影/电视</item>
        <item>图书</item>
        <item>唱片</item>
        <item>小事</item>
        <item>用户</item>
        <item>小组</item>
        <item>群聊</item>
        <item>游戏/应用</item>
        <item>活动</item>
    </string-array>
</resources>

三、运行结果


原文地址:https://blog.csdn.net/m0_74972727/article/details/136524657

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!