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

Android Studio中动态生成TextView及数组列表实现问题求助

从数组生成列表的实现方法&你现有代码的问题

首先说你当前代码没显示内容的原因:你只创建了TextView对象,但没有把它添加到当前界面的布局容器里,Android里所有要显示的View都得加入到布局层级中才能被渲染出来。

如果只是要显示这个TextView,修改代码如下(假设你的布局里有一个id为container的LinearLayout作为容器):

public void view(View v){
    TextView t = new TextView(viewAuto.this);
    t.setTextColor(Color.RED);
    t.setText("PIPPO");
    // 获取布局容器
    LinearLayout container = findViewById(R.id.container);
    // 将TextView添加到容器中
    container.addView(t);
}

但你要的是从数组生成项目列表,这时候用TextView一个个加太麻烦,Android有专门的列表控件,新手先从简单的ListView入手:

用ListView实现数组列表

1. 在布局文件中添加ListView

打开你的Activity布局文件(比如activity_main.xml),加入ListView:

<ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

2. 在Activity中绑定数组数据

在你的viewAuto类的onCreate方法里写以下代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 你的数组数据
    String[] projectList = {"项目A", "项目B", "项目C", "项目D"};
    // 获取ListView控件
    ListView listView = findViewById(R.id.list_view);
    // 创建适配器,把数组和列表绑定
    // android.R.layout.simple_list_item_1是系统自带的简单文本布局,适合新手
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_list_item_1, projectList);
    // 给ListView设置适配器
    listView.setAdapter(adapter);
}

这样运行后就能直接看到数组生成的列表了。

如果之后需要自定义列表项的样式(比如加图标、多行文本),可以自己写一个item布局文件,然后自定义适配器,但先把这个简单的版本跑通再说。

内容的提问来源于stack exchange,提问作者Gio

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 12:10:07