如何在 Android TextView 中连接文本?

4
我希望你能够在Android中拼接两个文本并用单个TextView显示。我尝试了以下类型,它只在logcat中显示,但没有在XML TextView中拼接。
这是我的代码:
<TextView
              android:id="@+id/heizgriffe"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Heizgriffe"
              android:textColor="#000"
              android:textSize="12dp"
              android:textStyle="bold"

              android:layout_below="@+id/txt"/>

在Java类中:

txtConcat = (TextView)findViewById(R.id.txt);
String hub="Hubraum:";
            String str= ItemList.getTxt(); // fetting from webservice
            txtConcat .setText(hub + str );

这里有什么问题吗?

5个回答

2

你想要做的事情并不像你看到的那么复杂,确实,你得到的结果并不是你想要的,看着你的代码,我可以说甚至程序都不能编译,因为它一定会生成语法错误。这是因为你不能使用setText来连接文本。解决方案可以是以下内容。

XML文件:

<TextView
android:id="@+id/tvInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />

Java类:

public TextView tvInfo;
private java.lang.CharSequence ID = "8945213624";

TextView tvInfo = (TextView)findViewById(R.id.tvInfo);
tvInfo.setText("My ID number is: ");
tvInfo.append(ID);

结果如下:

我的ID号码是:8945213624

你的代码没有问题,只需要正确使用连接元素,就像我展示的那样,使用append来连接元素。


2
txtConcat = (TextView)findViewById(R.id.txt); // initialize
String hub="Hubraum:";
String str= ItemList.getTxt(); // fetching from webservice
txtConcat .setText(hub + str );

1
抱歉,我只能这样使用,但它并不是拼接。 - selva
字符串连接在相对布局中运行良好,但在线性布局下无法正常工作。有人知道这个问题的原因吗? - selva
现在它正在工作,这里我错误地将txtConcat.setText()放了两次,所以只有那个时候它不起作用。 - selva

-1
String str= (String) ItemList.getTxt();

试一下这个


-1

txtConcat = (TextView)findViewById(R.id.txt);

难道不应该是: txtConcat = (TextView)findViewById(R.id.heizgriffe);


-1

可以尝试以下答案……

String hub="Hubraum:";
String str= hub+ItemList.getTxt(); // fetcting from webservice
txtConcat.setText(str );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接