我想将TextViews膨胀到LinearLayout。

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

java - 将TextViews膨胀到LinearLayout-LMLPHP

现在,我尝试根据变量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;
}


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

java - 将TextViews膨胀到LinearLayout-LMLPHP

如您所见,它在底部添加了TextViews。因此,我从activity_play_game删除了所有TextView,并添加LinearLayout来充气TextView:

java - 将TextViews膨胀到LinearLayout-LMLPHP

如何在按钮上方将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类中:

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;
}

关于java - 将TextViews膨胀到LinearLayout,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43757630/

10-10 01:10