如何通过串联两个字符串来创建新的“ TextView”对象?

时间:2019-01-11 19:01:22

标签: android

我想通过级联在“ MainActivity”代码中创建一个新的“ TextView”对象 两个字符串名称。例如:

String s1 = "num";
String s2 = "ber";
String s3 = s1+s2;
TextView s3 = new TextView(this);

如何将s3强制转换为TextView对象,所以上面的代码不会出现任何错误? 我的意思是我想使用s3作为“ TextView”名称对象。

3 个答案:

答案 0 :(得分:1)

您会做这样的事情。

TextView textView = new TextView(this);
textView.setText(s3);

TextView s3 = new TextView(this);
s3.setText(s1 + s2);

或以编程方式循环

for (int i = 0; i < list.size(); i++) {
    TextView textView = new TextView(this);
    textView.setId(s3); //set textview id, this WILL NOT make it a variable of 'number'
    linearLayout.addView(textView);

}

答案 1 :(得分:0)

第一个问题是您声明了两个具有相同名称的变量。通过给TextView一个更好的名称来修复它,然后在@soldforapp已经回答时,使用方法.setText();

设置文本。

编辑:

等等,因此您想将TextView的值分配给字符串变量s3吗? 我不太了解您的问题。如果是这样,如果您的代码看起来像这样(这样就可以运行)

String s1 = "num";
String s2 = "ber";
String s3 = s1+s2;
TextView tv = new TextView(this);

此行将为变量s3分配TextView中的文本。

s3 = tv.getText().toString();

答案 2 :(得分:0)

在JAVA中,不可能在一个范围内为不同变量使用相同的名称。 (即使类型不同)

使用StringBuilder比通过+操作进行连接更好,因此:

String s1 = "num";
String s2 = "ber";
String concat = new StringBuilder().append(s1).append(s2).toString();

TextView s3 = new TextView(this);
s3.setText(concat);

编辑: 您想要的东西并不像PHP这样的脚本语言中的东西那么容易,但是您可以通过反思来实现。但是使用Map有一个更简单的选择:

Map<String,TextView> map = new HashMap<>();
map.put(concat, new TextView(this));

您可以通过以下方式获得TextViews

map.get(concat).setText("Your String");

相关问题