将 TextView 膨胀为 LinearLayout

Inflate TextViews to LinearLayout

我想将 TextViews 膨胀为 LinearLayout。

我有一个布局 activity_play_game 和 java class PlayGameActivity。 目前,对于硬编码数量的 TextView,它看起来像这样:

现在我尝试根据变量numberForbiddenWords的值添加TextViews的数量。我添加了一段代码,如下所示:

LinearLayout playGame = (LinearLayout) findViewById(R.id.activity_play_game);
TextView temp;
TextView[] textViews = new TextView[numberForbiddenWords];
for(int i = 0; i < numberForbiddenWords; i++) {
    temp = new TextView(this);
    playGame.addView(temp);
    textViews[i] = temp;
}

我有一个方法可以将 textView 添加到 activity_play_game。不幸的是现在它看起来像这样:

如您所见,它在底部添加了 TextView。所以我从 activity_play_game 中删除了所有 TextViews 并添加了 LinearLayout 来膨胀 TextViews:

如何将 TextViews 膨胀到按钮上方的这个 LinearLayout? 我找到了那种解决方案:

activity_to_add_words:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

在java class:

final View addView;
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
addView = layoutInflater.inflate(R.layout.activity_to_add_words,
        null);
final TextView textOut = (TextView) addView.findViewById(R.id.textout);

但这是 View,而不是 TextView。你知道怎么做吗?

获取您的 LinearLayout container_blue 的参考并向其添加 TextView's

试试这个:

LinearLayout playGame = (LinearLayout) findViewById(R.id.container_blue);
TextView temp;
TextView[] textViews = new TextView[numberForbiddenWords];
for(int i = 0; i < numberForbiddenWords; i++) {
    temp = new TextView(this);
    temp.setText("TextView " + String.valueOf(i));
    temp.setId(i);
    temp.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

    playGame.addView(temp);
    textViews[i] = temp;
}

像这样使用 textview 制作一个布局文件:

layout_textview.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="@+id/txt_spin"
android:textSize="18sp"
android:background="#fff"
android:padding="5dp"
android:textColor="#000"
android:layout_height="wrap_content"/>

然后在您的 java 文件中应用以下代码:

 LinearLayout playGame = (LinearLayout) findViewById(R.id.container_blue);      
 LayoutInflater li =(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View view = li.inflate(R.layout.layout_textview, null);
 TextView txt= (TextView) view.findViewById(R.id.txt_spin);
 playGame.addView(view);

希望它对你有用...编码愉快..:)

据我所知,您最初的问题是关于在三个按钮之前动态添加项目。如果您想在三个按钮之前添加它们,只需调用 playGame.addView(temp,0); 这将始终将项目添加到布局中的第一个位置。 如果您需要添加视图的特定顺序,您需要使用 for 循环以正确的顺序添加它们。