簡體   English   中英

If ... Else 語句似乎返回錯誤的輸出

[英]If ... Else statement seems to be returning the wrong output

我只是探索不同的方法來測試 java 中的 Log 類,如果顯示某個文本視圖,我使用 Log.d() 和 Log.e() 記錄異常錯誤,否則。

但是,logcat 似乎顯示相反的輸出。 為什么呢?

我的主要活動代碼:

package com.example.dummy_app;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (findViewById(R.id.editText).toString().equals("Happy Birthday!")) {
            Log.d("logMessage", "correct message shown");
        } else {
            Log.e("logMessage", "exception error");
        }
    }
}

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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Happy Birthday!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

logcat 顯示“異常錯誤”而不是“顯示正確消息”。 我也嘗試刪除toString()但它仍然顯示相同的結果。 誰能解釋為什么? 在此處輸入圖片說明

改變:

findViewById(R.id.editText).toString().equals("Happy Birthday!")

到:

findViewById(R.id.editText).text.toString().equals("Happy Birthday!")

您的問題與以下聲明有關,

findViewById(R.id.editText).toString().equals("Happy Birthday!")

不要像那樣聲明TextView 這不是一個好習慣。 首先,聲明你的 TextView 如下,

TextView textView = (TextView) findViewById(R.id.textView);

現在你終於可以用它做任何你想做的事情了,比如按如下方式獲取輸入,

String inputTxt = textView.getText().toString();

所以你的完整代碼應該如下所示,

package com.example.dummy_app;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        TextView textView = (TextView) findViewById(R.id.textView);

        if (textView.getText().toString().equals("Happy Birthday!")) {
            Log.d("logMessage", "correct message shown");
        } else {
            Log.e("logMessage", "exception error");
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM