如何通过连接两个字符串来创建新的"TextView"对象?



我想在"MainActivity"代码中创建一个新的"TextView"对象,方法是连接两个字符串名称。例如:

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

如何将s3转换为TextView对象,所以我没有收到任何错误,上面的代码?我的意思是我想使用 s3 作为"文本视图"名称对象。

你会做这样的事情。

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);
}

第一个问题是你声明了 2 个同名变量。通过为 TextView 提供一个更好的名称来修复它,然后按照@soldforapp已经回答的那样,使用方法 .setText();

编辑:

等等,所以你想将文本视图的值分配给字符串变量 s3?我真的不明白你的问题。如果是这样,如果你的代码看起来像这样(所以它运行)

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

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

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

在一个作用域中对不同的变量使用相同的名称在 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");

最新更新