You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 15:06:04