首页 > 解决方案 > 通过for循环创建TextView,只有第一个创建的工作

问题描述

我正在尝试创建一个 TextView 的早午餐并通过 for 循环在屏幕上显示它们。

但只有第一个 TextView 显示分配的值“123”。

仍然创建了许多 TextView 但只有第一个显示值。

我想我错过了什么,但你知道我错过了什么吗?

谢谢。

创建():

 LinearLayout busStopLinearLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        
        // skipped

        busStopLinearLayout = (LinearLayout) findViewById(R.id.bus_stop_linear_layout);

        // skipped

    }

我要求的 for 循环:

    for (int i = 0; i < closestStop.size(); i++) {
        TextView dummyTxt = new TextView(MainActivity.this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);

        dummyTxt.setLayoutParams(params);

        dummyTxt.setText("123");

        busStopLinearLayout.addView(dummyTxt);

        busStopTextArray.add(dummyTxt);
    }

活动.xml

        <LinearLayout
            android:id="@+id/bus_stop_linear_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:baselineAligned="false"
            android:orientation="horizontal">

标签: androidfor-looptextview

解决方案


试试这个

LinearLayout busStopLinearLayout = (LinearLayout) findViewById(R.id.busStopLinearLayout); 
for(int i=0; i<closestStop.size(); i++){
    TextView text = new TextView(this);
    text.setText("123");
    text.setTextSize(12);
    text.setGravity(Gravity.LEFT);
    text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    busStopLinearLayout.addView(text);
}

推荐阅读