Android开发出现Cannot resolve method 'setText(java.lang.String[])'报错如何修正
报错原因
setText()是TextView提供的原生方法,仅支持传入String、CharSequence等类型参数,你传入的Description是String[]字符串数组类型,类型不匹配所以触发编译报错。
需修正的两处问题
- 第一处是变量遮蔽隐患:你已经在类顶部声明了成员变量
private TextView tvdescription,但在onCreate方法中又重复声明了局部同名变量,后续赋值操作仅作用于局部变量,属于代码逻辑隐患。 - 第二处是参数类型不匹配:需要先将字符串数组转换为字符串类型再传入
setText()方法。
修正后代码
public class Book_Activity extends AppCompatActivity { private TextView tvtitle,tvdescription,tvcategory; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_book); tvtitle = findViewById(R.id.txttitle); // 移除重复的TextView声明,直接给成员变量赋值 tvdescription = findViewById(R.id.txtdes); tvcategory = findViewById(R.id.txtcat); img = findViewById(R.id.bookthumbnail); // 接收数据 Intent intent = getIntent(); String Title = intent.getExtras().getString("Title"); String Category = intent.getExtras().getString("Category"); String[] Description = intent.getExtras().getStringArray("Description"); int image = intent.getExtras().getInt("Thumbnail") ; // 设置数值 tvtitle.setText(Title); tvcategory.setText(Category); // 示例用换行符拼接数组所有元素,可根据业务需求调整拼接规则 tvdescription.setText(TextUtils.join("\n", Description)); img.setImageResource(image); } }
可选替换方案
如果不想引入TextUtils工具类,也可以手动遍历数组拼接字符串:
StringBuilder desBuilder = new StringBuilder(); for (String desItem : Description) { desBuilder.append(desItem).append("\n"); } tvdescription.setText(desBuilder.toString());
如果你的Description数组仅包含一个有效元素,直接取数组下标对应值即可:
tvdescription.setText(Description[0]);
内容的提问来源于stack exchange,提问作者ZULFAN AHMADI
相关产品推荐
相关产品推荐

