【发布时间】:2019-09-15 06:16:08
【问题描述】:
我正在尝试在 MainActivity.java 中设置文本,但该文本未能出现在模拟器中。
我的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"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="204dp"
android:text="Show Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="2dp"
android:layout_height="17dp"
android:layout_marginTop="76dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
我的 MainActivity.java
> package com.example.shownamenow;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private TextView showText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = findViewById(R.id.button);
showText = findViewById(R.id.textView);
showText.setText("Hello I am here!");
}
}
我在 MainActivity.java 中遇到错误,提示“setText 中的字符串文字无法翻译。使用 android 资源...”。所以我改用字符串资源:showText.setText(R.String.Hello) 并在 strings.xml 中创建了值为“Hello I am here”的资源。仍然当我在模拟器中加载应用程序时,文本拒绝出现。我做错了什么???
【问题讨论】:
-
分享错误日志。
-
将
layout_width="wrap_content"与constraintEnd_toEndOf="parent"和constraintStart_toStartOf="parent"一起使用是没有意义的,因为无论如何它都会拉伸它,所以layout_width="wrap_content"不会产生任何影响。这里的问题是高度太小,如果您不提供这两个约束,只需使用layout_height="wrap_content"。 -
设置 textview 宽度为 0dp 或匹配父级
标签: java android textview settext