簡體   English   中英

將TextViews膨脹到LinearLayout

[英]Inflate TextViews to LinearLayout

我想將TextViews膨脹到LinearLayout。

我有一個布局activity_play_game和java類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;
}

我有一個方法可以將textViews添加到activity_play_game 不幸的是,現在看起來像這樣:

在此處輸入圖片說明

如您所見,它在底部添加了TextViews。 因此,我從activity_play_game刪除了所有TextView,並添加LinearLayout來充氣TextView:

在此處輸入圖片說明

如何在按鈕上方將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;
}

使用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循環以正確的順序添加它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM