我只是在探索不同的方法来测试java中的Log类,如果显示某个 TextView ,我使用Log.d(),否则使用Log.e()记录异常错误。
但是,logcat 似乎显示相反的输出。为什么会这样?
我的主要 Activity 代码:
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!")
不要声明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");
}
}
}
关于java - If ... Else 语句似乎返回错误的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59067317/