2 微调器和 if 语句

2 Spinners and if statements

我正在构建一个单位换算应用程序。我需要有一个输入和 2 个微调器。微调器调节当前单位是什么,以及新单位将是什么。下面是我的代码。我对如何使用 if 语句来比较两者感到困惑。我一直在尝试使用 .equals("lb"),但由于某种原因它只是 returns false。让我知道我可能哪里出错了。

主要代码:

package com.stproductions.commonconverter;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

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

        //Convert From Box
        setContentView(R.layout.activity_main);
        Spinner spinner1 = findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence>adapter1 = ArrayAdapter.createFromResource(this, R.array.fromchoices, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spinner1.setAdapter(adapter1);
        spinner1.setOnItemSelectedListener(this);

        //Convert To Box
        Spinner spinner2 = findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence>adapter = ArrayAdapter.createFromResource(this, R.array.choices, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spinner2.setAdapter(adapter);
        spinner2.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String text = parent.getItemAtPosition(position).toString();
        String text2 = parent.getItemAtPosition(position).toString();
//        View text = parent.findViewById(R.id.spinner1);
//        View text2 = parent.findViewById(R.id.spinner2);
//        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
//        Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);

        if(text.equals("lb") && text2.equals("oz")){
            Toast.makeText(this,"hello", Toast.LENGTH_SHORT).show();
        }
    }

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

    }
}

String.XML:

<resources>
    <string name="app_name">Common Converter</string>

        <string-array name="choices">
            <item>lb</item>
            <item>oz</item>
            <item>g</item>
            <item>kg</item>
            <item>ton</item>
            <item>mg</item>
        </string-array>

    <string-array name="fromchoices">
        <item>lb</item>
        <item>oz</item>
        <item>g</item>
        <item>kg</item>
        <item>ton</item>
        <item>mg</item>
    </string-array>

</resources>

Activity_Main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="#FFFFFF"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="97dp"
        android:layout_height="59dp"
        android:background="#E6E6E6"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.831"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.595" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="97dp"
        android:layout_height="59dp"
        android:background="#E6E6E6"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.831"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.309" />


</androidx.constraintlayout.widget.ConstraintLayout>

我现在在 logcat 中得到以下内容:

2021-01-06 14:48:00.985 18954-18954/com.stproductions.commonconverter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.stproductions.commonconverter, PID: 18954
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.view.View.toString()' on a null object reference
    at com.stproductions.commonconverter.MainActivity.onItemSelected(MainActivity.java:39)
    at android.widget.AdapterView.fireOnSelected(AdapterView.java:957)
    at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:946)
    at android.widget.AdapterView.access0(AdapterView.java:55)
    at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:910)
    at android.os.Handler.handleCallback(Handler.java:938)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7656)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

编辑: 首先,正如我在此答案下方的评论中所说,一旦您 select 来自 [=] 的值,您的 onItemSelected 就会被调用16=] 并且当您 select 来自 Spinner2 的值时再次出现。每次,texttext2 都是相同的值,因此将它们与不同的值进行比较永远不会成立。你需要另一种方法。

要做到这一点,不用 .setOnItemSelectedListener() 也可以做到这一点。我像这样将 Button 添加到您的布局中:

<Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="Click"
        android:id="@+id/button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.831"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.309"/>

在那之后,在你的 MainActivity.class 中,我删除了 spinner1.setOnItemSelectedListener(this)spinner2.setOnItemSelectedListener(this),并添加了 btn.setOnClickListener(),如下所示:

Button btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (spinner1.getSelectedItem() != null && spinner2.getSelectedItem() != null) {
                    String first_option = spinner1.getSelectedItem().toString();
                    String second_option = spinner2.getSelectedItem().toString();

                    if (first_option.contentEquals(second_option)) {
                        Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "sad face", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

所以现在你甚至不需要听众了。检查微调器是否等于 null 如果它是你应该通过通知用户他需要 select 任何值来处理它。如果默认情况下您的值是 selected,则不需要这样做。现在您可以在这个 onClick 方法中创建 switch case 并根据需要显示您的输出。

无论如何,我对使用 string.contentEquals() 的建议仍然有效。

这是我的最终代码:

MainActivity.class

public class MainActivity extends AppCompatActivity {

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

        //Convert From Box
        Spinner spinner1 = findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence>adapter1 = ArrayAdapter.createFromResource(this, R.array.fromchoices, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spinner1.setAdapter(adapter1);

        //Convert To Box
        Spinner spinner2 = findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence>adapter = ArrayAdapter.createFromResource(this, R.array.choices, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        spinner2.setAdapter(adapter);

        Button btn = findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (spinner1.getSelectedItem() != null && spinner2.getSelectedItem() != null) {
                    String first_option = spinner1.getSelectedItem().toString();
                    String second_option = spinner2.getSelectedItem().toString();

                    if (first_option.contentEquals(second_option)) {
                        Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "sad face", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="#FFFFFF"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="97dp"
        android:layout_height="59dp"
        android:background="#E6E6E6"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.831"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.595" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="97dp"
        android:layout_height="59dp"
        android:background="#E6E6E6"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.831"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.309" />

    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:text="Click"
        android:id="@+id/button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.831"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.309"/>


</androidx.constraintlayout.widget.ConstraintLayout>

您应该使用 string.contentEquals() 而不是 string.equals()。原因是 string.equals() 比较字符串的内容,但它也会检查另一个对象是否也是 String 的实例。 String.contentEquals() 只比较对象的内容。所以它可以是 CharSequence 或任何类似的东西,String、StringBuilder 等。

你在onCreate

中还有一个额外的setContentView()
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Convert From Box
        setContentView(R.layout.activity_main); <--- DELETE THIS LINE
        Spinner spinner1 = findViewById(R.id.spinner1);

来源:

String#equals()

String#contentEquals()

第 1 点: 实际上你对 SpinnerSpinner2 使用相同的 AdapterView.OnItemSelectedListener.. 所以相同的 onItemSelected() 当您 select 两个微调器中的任何一个的值时,将触发回调。

第 2 点: onItemSelected() 中的第二个点 texttext2 具有相同的值.. 我猜你认为 text 将指向 Spinner1 selected 项,而 text2 将指向 Spinner2 selected 项;从第 1 点开始,这是错误的。

所以要解决这个问题:您可以为微调器使用不同的 listener/callback,或者使用相同的 listener/callback 但做一些逻辑来区分哪个微调器触发 onItemSelected() 回调.

我在这里使用 id 属性来了解哪个微调器触发 onItemSelected()

我将两个微调器都设为全局字段以方便访问它们。并放置一个 Toast 来显示微调器的任何更改的值。

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private static final String TAG = "LOG_TAG";
    private Spinner mSpinner2;
    private Spinner mSpinner1;

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

        //Convert From Box
        setContentView(R.layout.activity_main);
        mSpinner1 = findViewById(R.id.spinner1);
        ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.fromchoices, android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mSpinner1.setAdapter(adapter1);
        mSpinner1.setOnItemSelectedListener(this);

        //Convert To Box
        mSpinner2 = findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.choices, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
        mSpinner2.setAdapter(adapter);
        mSpinner2.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String text = "", text2 = "";
        if (parent.getId() == R.id.spinner1) {
            Log.d(TAG, "onItemSelected: spinner 1");
            text = parent.getItemAtPosition(position).toString();
            text2 = mSpinner2.getSelectedItem().toString();
        } else if (parent.getId() == R.id.spinner2) {
            Log.d(TAG, "onItemSelected: spinner 1");
            text2 = parent.getItemAtPosition(position).toString();
            text = mSpinner1.getSelectedItem().toString();
        }
        Toast.makeText(this, "Spinner1: " + text + " Spinner2: " + text2, Toast.LENGTH_SHORT).show();


//        View text = parent.findViewById(R.id.spinner1);
//        View text2 = parent.findViewById(R.id.spinner2);
//        Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
//        Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);

        if (text.equals("lb") && text2.equals("oz")) {
            Toast.makeText(this, "hello", Toast.LENGTH_SHORT).show();
        }
    }

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

    }
}