Android:在点击任何项目之前在微调器中显示提示

时间:2018-04-18 12:01:39

标签: android spinner hint

我的程序是设计一个带有提示词的微调器"简介"在单击微调器的箭头以选择项目之前,当我单击箭头时,它将显示一个包含多个项目的下拉菜单,但我不希望提示词显示为投影中的一个项目 - 下拉菜单。当我点击微调器内的一个项目时,它会将我引导到相应的片段。

在添加提示词之前,我的程序能够顺利运行。但是,在我使用提示功能修改我的代码后,我无法再运行它了.......

到目前为止,我的程序能够在我运行时展示第一个布局,但每次单击微调器的箭头时它都会消失,显示"应用已停止"。  (我的程序中没有消息错误,但是在logcat和运行中有一些线索,我尝试读取它们但仍然无法理解)

我的提示修订版基于以下网站:

How to make an Android Spinner with initial text "Select One"

https://android--code.blogspot.tw/2015/08/android-spinner-hint.html

和其他一些网站,但大多数网站都很复杂,像我这样的新手修改以满足我的需求。 非常感谢你帮我解决><

MainActivity.java:     package com.example.ellen.spinnercontent;

import android.graphics.Color;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import android.widget.TextView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // Get reference of widgets from XML layout
        final Spinner sp = findViewById(R.id.spi);

//        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.ar.planets_array, android.R.layout.simple_spinner_item);
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
//        sp.setPrompt("Introduction");

        // Initialize a String Array
        final String[] section = {
                "Introduction",
                "Slide design",
                "Slide written content",
                "Introduction language",
                "Body language",
                "Full example of a good introduction",

        };


        // Initializing an ArrayAdapter with the string section
        final ArrayAdapter<String> ar = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, section){

            @Override
            public boolean isEnabled(int position){
                if(position == 0)
                {
                    // Disable the first item(hint) from Spinner
                    return false;
                }
                else
                {
                    return true;
                }
            }

            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent)
            {
                View view = super.getDropDownView(position, convertView, parent);

                TextView tv = (TextView) view;
                if(position == 0){
                    // Set the hint text color gray
                    tv.setTextColor(Color.GRAY);
                }
                else {
                    tv.setTextColor(Color.BLACK);
                }
                return view;
            }
        };

        ar.setDropDownViewResource(R.layout.spinner_item);//added

        sp.setAdapter(ar);

        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {

            private void changeFragment(Fragment fragment) {
                FragmentTransaction ta = getSupportFragmentManager().beginTransaction();
                ta.replace(R.id.root, fragment);
                ta.addToBackStack(null);
                ta.commit();
            }

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
            {
                String s = (String) parent.getItemAtPosition(position);


                if(position > 0)
                {

                    if (s.equals("Slide design"))
                        changeFragment(new FragmentOne());

                    if (s.equals("Slide written content"))
                        changeFragment(new FragmentTwo());

                    if (s.equals("Introduction language"))
                        changeFragment(new FragmentThree());

                    if (s.equals("Body language"))
                        changeFragment(new FragmentFour());

                    if (s.equals("Full example of a good introduction"))
                        changeFragment(new FragmentFive());
                }
            }
            public void onNothingSelected(AdapterView<?> arg0) {
            }

        });
    }
}

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:orientation="vertical"
    tools:context="com.example.ellen.spinnercontent.MainActivity">


    <Spinner
        android:id="@+id/spi"
        android:textSize="26sp"
        android:textStyle="normal|bold"
        android:ellipsize="marquee"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingStart="8dip"
        android:paddingLeft="8dip"
        android:paddingRight="8dip"
        android:singleLine="true"
        android:textColor="#8B008B"
        />


    <RelativeLayout
        android:id="@+id/root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        xmlns:tools="http://schemas.android.com/tools"
        android:padding="10dp"
        tools:context=".MainActivity"
        android:background="#fbdfed"
        />


</LinearLayout>

spinner_item.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:orientation="vertical"
tools:context="com.example.ellen.spinnercontent.MainActivity">


    <TextView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textStyle="italic"
        />

</LinearLayout>

运行:

04/18 19:07:09: Launching app
$ adb push /Users/ellen/Desktop/my-spinner/spinnerContent/app/build/outputs/apk/debug/app-debug.apk /data/local/tmp/com.example.ellen.spinnercontent
$ adb shell pm install -t -r "/data/local/tmp/com.example.ellen.spinnercontent"
Success


$ adb shell am start -n "com.example.ellen.spinnercontent/com.example.ellen.spinnercontent.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 3477 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/System: ClassLoader referenced unknown path: /data/app/com.example.ellen.spinnercontent-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0xa07050c0: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xa07050c0: ver 2 0 (tinfo 0xa07036c0)
D/EGL_emulation: eglMakeCurrent: 0xa07050c0: ver 2 0 (tinfo 0xa07036c0)
E/ArrayAdapter: You must supply a resource ID for a TextView
D/AndroidRuntime: Shutting down VM


                  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.ellen.spinnercontent, PID: 3477
                  java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
                      at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
                      at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:457)
                      at com.example.ellen.spinnercontent.MainActivity$1.getDropDownView(MainActivity.java:75)
                      at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:975)
                      at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:971)
                      at android.widget.Spinner.measureContentWidth(Spinner.java:845)
                      at android.widget.Spinner$DropdownPopup.computeContentWidth(Spinner.java:1206)
                      at android.widget.Spinner$DropdownPopup.show(Spinner.java:1232)
                      at android.widget.Spinner.performClick(Spinner.java:770)
                      at android.support.v7.widget.AppCompatSpinner.performClick(AppCompatSpinner.java:448)
                      at android.view.View$PerformClick.run(View.java:22429)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
                      at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:388)
                      at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:457) 
                      at com.example.ellen.spinnercontent.MainActivity$1.getDropDownView(MainActivity.java:75) 
                      at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:975) 
                      at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:971) 
                      at android.widget.Spinner.measureContentWidth(Spinner.java:845) 
                      at android.widget.Spinner$DropdownPopup.computeContentWidth(Spinner.java:1206) 
                      at android.widget.Spinner$DropdownPopup.show(Spinner.java:1232) 
                      at android.widget.Spinner.performClick(Spinner.java:770) 
                      at android.support.v7.widget.AppCompatSpinner.performClick(AppCompatSpinner.java:448) 
                      at android.view.View$PerformClick.run(View.java:22429) 
                      at android.os.Handler.handleCallback(Handler.java:751) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6119) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
Application terminated.

logcat的:

04-18 18:49:42.329 3536-3536/? I/art: Not late-enabling -Xcheck:jni (already on)
04-18 18:49:42.330 3536-3536/? W/art: Unexpected CPU variant for X86 using defaults: x86
04-18 18:49:42.490 3536-3536/com.example.ellen.spinnercontent W/System: ClassLoader referenced unknown path: /data/app/com.example.ellen.spinnercontent-3/lib/x86
04-18 18:49:42.569 3536-3536/com.example.ellen.spinnercontent W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-18 18:49:42.902 3536-3553/com.example.ellen.spinnercontent I/OpenGLRenderer: Initialized EGL, version 1.4
04-18 18:49:42.902 3536-3553/com.example.ellen.spinnercontent D/OpenGLRenderer: Swap behavior 1
04-18 18:49:42.909 3536-3553/com.example.ellen.spinnercontent W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
04-18 18:49:42.909 3536-3553/com.example.ellen.spinnercontent D/OpenGLRenderer: Swap behavior 0
04-18 18:49:42.946 3536-3553/com.example.ellen.spinnercontent D/EGL_emulation: eglCreateContext: 0xaf8850c0: maj 2 min 0 rcv 2
04-18 18:49:42.980 3536-3553/com.example.ellen.spinnercontent D/EGL_emulation: eglMakeCurrent: 0xaf8850c0: ver 2 0 (tinfo 0xaf8834d0)
04-18 18:49:43.046 3536-3553/com.example.ellen.spinnercontent D/EGL_emulation: eglMakeCurrent: 0xaf8850c0: ver 2 0 (tinfo 0xaf8834d0)
04-18 18:50:12.385 3536-3536/com.example.ellen.spinnercontent E/ArrayAdapter: You must supply a resource ID for a TextView
04-18 18:50:12.386 3536-3536/com.example.ellen.spinnercontent D/AndroidRuntime: Shutting down VM


                                                                                --------- beginning of crash
04-18 18:50:12.392 3536-3536/com.example.ellen.spinnercontent E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ellen.spinnercontent, PID: 3536
                                                                                java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
                                                                                    at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)
                                                                                    at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:457)
                                                                                    at com.example.ellen.spinnercontent.MainActivity$1.getDropDownView(MainActivity.java:75)
                                                                                    at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:975)
                                                                                    at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:971)
                                                                                    at android.widget.Spinner.measureContentWidth(Spinner.java:845)
                                                                                    at android.widget.Spinner$DropdownPopup.computeContentWidth(Spinner.java:1206)
                                                                                    at android.widget.Spinner$DropdownPopup.show(Spinner.java:1232)
                                                                                    at android.widget.Spinner.performClick(Spinner.java:770)
                                                                                    at android.support.v7.widget.AppCompatSpinner.performClick(AppCompatSpinner.java:448)
                                                                                    at android.view.View$PerformClick.run(View.java:22429)
                                                                                    at android.os.Handler.handleCallback(Handler.java:751)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                 Caused by: java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
                                                                                    at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:388)
                                                                                    at android.widget.ArrayAdapter.getDropDownView(ArrayAdapter.java:457) 
                                                                                    at com.example.ellen.spinnercontent.MainActivity$1.getDropDownView(MainActivity.java:75) 
                                                                                    at android.widget.Spinner$DropDownAdapter.getDropDownView(Spinner.java:975) 
                                                                                    at android.widget.Spinner$DropDownAdapter.getView(Spinner.java:971) 
                                                                                    at android.widget.Spinner.measureContentWidth(Spinner.java:845) 
                                                                                    at android.widget.Spinner$DropdownPopup.computeContentWidth(Spinner.java:1206) 
                                                                                    at android.widget.Spinner$DropdownPopup.show(Spinner.java:1232) 
                                                                                    at android.widget.Spinner.performClick(Spinner.java:770) 
                                                                                    at android.support.v7.widget.AppCompatSpinner.performClick(AppCompatSpinner.java:448) 
                                                                                    at android.view.View$PerformClick.run(View.java:22429) 
                                                                                    at android.os.Handler.handleCallback(Handler.java:751) 
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                                    at android.os.Looper.loop(Looper.java:154) 
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                                    at java.lang.reflect.Method.invoke(Native Method) 
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

1 个答案:

答案 0 :(得分:0)

我也遇到过类似的问题。通过这个链接,我希望它可以帮助你!

https://stackoverflow.com/a/12221309/6388699

也要牢记这一点:

  1. 通常,适配器中的第一个选项会显示给用户。该 NothingSelectedSpinnerAdapter可让您显示“选择” ......“而不是第一选择。
  2. 因此我们需要设置nominee_relationship_et.setSelection(pos+1);以正确显示项目(忽略第一项)。
  3. 另请注意,setOnItemSelectedListener被称为2次: 1)初始化期间2)项目点击。因此保持一个标志,以防止错误选择微调项目。