2微调器和if语句

unguejic  于 2021-06-26  发布在  Java
关注(0)|答案(2)|浏览(360)

我正在建立一个单位转换应用程序。我需要一个输入和两个微调器。微调器调节当前单位和新单位。下面是我的代码。我对如何使用if语句来比较两者感到困惑。我一直在尝试使用.equals(“lb”),但由于某些原因它只返回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) {

    }
}

字符串.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>

活动\u 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>

我现在在日志中得到以下信息:

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.access$300(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)
wnavrhmk

wnavrhmk1#

编辑:首先,就像我在下面的评论中说的,你的答案 onItemSelected 一旦从中选择值,将调用 Spinner1 当您从 Spinner2 . 每次, text 以及 text2 会有相同的值,所以比较它们永远不会是真的。你需要另一种方法。
这样做,而不是使用 .setOnItemSelectedListener() 你可以不用这个做这个。我在布局中添加了如下按钮:

<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();
                    }
                }
            }
        });

所以现在你甚至不需要你的听众了。检查spinner是否等于null,如果是,您应该通过通知用户需要选择任何值来处理它。如果您的值在默认情况下被选择为第一个,则不需要这样做。现在,您可以在这个onclick方法中创建switch案例,并根据需要显示输出。
不管怎样,我的建议是 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 ```

<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等等。
你还有一个额外的 `setContentView()` 在 `onCreate` ```
@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);

资料来源:
字符串#equals()
字符串#contentequals()

jgovgodb

jgovgodb2#

第一点:其实你用的是同一个 AdapterView.OnItemSelectedListener 两者皆适用 Spinner & Spinner2 .. 同样如此 onItemSelected() 当您选择两个微调器中的任何一个的值时,将触发回调。
第二点:第二点 text 以及 text2 内部 onItemSelected() 具有相同的值。。我想你应该知道 text 将指向 Spinner1 所选项目,以及 text2 将指向 Spinner2 所选项目;从第一点开始这是错误的。
所以要解决这个问题:您可以为微调器使用不同的侦听器/回调,也可以使用相同的侦听器/回调,但要执行一些逻辑来区分哪个微调器触发 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) {

    }
}

相关问题