首页 > 解决方案 > 如何在 XML 中编写段落并使用 Java 代码?

问题描述

在 XML 中编写段落和解析其中的 Java 变量时遇到问题。

我的变量是Name (user_input) ,屏幕上的预期结果是 Welcome + "Name"。

试过 System.out.println("Hello" + fname); 在 Java 文件中。尝试在 XML 文件中使用。

XML 代码:

<RelativeLayout 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">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">


        <TextView
            android:id="@+id/first"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text= "TextView" />
    </LinearLayout>
</RelativeLayout>

爪哇:

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class Feedback extends AppCompatActivity {

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

        Intent intent = getIntent();
        String text = intent.getStringExtra(MainActivity.fnamet);


        TextView fnamef =  findViewById(R.id.first);


        fnamef.setText(text);

        System.out.println("Welcome" + fnamef);

    }
}

我的 fname 变量是“John”,所以我们希望设备屏幕上的结果是“Hello John”,但是在 EditText 中输入名称并单击提交后,没有显示任何消息。

谢谢

标签: javaandroidxml

解决方案


首先,如果您提供启动Feedback活动的代码会更好。

来到答案,

fnamef.setText(text);

这只会将名称设置为TextView.

如果 text 的值为“John”,则它仅显示 John 在TextView.

如果要设置文本“Welcome John”,您可以执行以下操作:-

fnamef.setText("Welcome " + text);

如果您没有显示任何消息,那么我们希望查看您开始Feedback活动的代码。


推荐阅读