3

有很長的字符串。我將長串分成單詞併爲每個單詞設置TextView。 (?你可以問,爲什麼我需要這個功能,當用戶點擊的TextView(字),應用程序顯示了這個詞的含義)以編程方式將多個TextView添加到LinearLayout中

... 
    TextView tv = new TextView(this); 
       tv.setTextSize(24); 
       tv.setText(word); 
       ll.addView(tv); 
... 

我的LinearLayout:

<LinearLayout 
     android:id="@+id/llReader" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_marginLeft="10dp" 
     android:layout_marginRight="10dp" 
     android:orientation="vertical" > 
    </LinearLayout> 

如果我把LinearLayout中的定位垂直,它將每個TextView放在新的行中。 例如:

字1

單詞2

WORD3

如果我把它在水平方向,它把所有的話只有一個行:

字1,字2,字3

在結果word4中,word5,word6不可見。

如何以這種方式編程添加TextViews?

enter image description here

回答

0

在您的活動,

private LinearLayout mReaderLayout; 

protected void onCreate(Bundle savedInstanceState) { 
    mReaderLayout = (LinearLayout) findViewById(R.layout.llReader); 
} 

private void addText(String text) { 
    TextView textView = new TextView(this); 
    textView.setText(text); 
    mReaderLayout.addView(textView); 
} 
+0

首先,感謝您的回答。但是我問了如何在圖片中顯示的方式將textview添加到linearlayout中:TextViews的段落 – user3388473

0

您可以使用GridView控件與適配器。

<GridView 
        android:id="@+id/gridview1" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:columnWidth="50dp" 
        android:gravity="center" 
        android:numColumns="auto_fit" 
        android:stretchMode="columnWidth" > 

       </GridView> 

onCreate

String[] strings= "Long string".split(" "); 
     gridView = (GridView) findViewById(R.id.gridview1); 

       // Create adapter to set value for grid view 
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
         android.R.layout.simple_list_item_1, strings); 

       gridView.setAdapter(adapter); 

       gridView.setOnItemClickListener(new OnItemClickListener() { 

        @Override 
        public void onItemClick(AdapterView<?> parent, View v, 
         int position, long id) { 

         Toast.makeText(getApplicationContext(), 
         ((TextView) v).getText() , Toast.LENGTH_SHORT).show(); 

        } 
       }); 
0

您可以添加使用的RelativeLayout馬上也可以在一個直線,垂直佈局添加兩個按鈕,然後添加到一個水平佈局。然後將其他兩個按鈕的下一個垂直線性佈局添加到水平佈局中。

2

您應該添加水平的LinearLayout垂直的LinearLayout

所有的
<LinearLayout 
    android:id="@+id/verticalLinear" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 
    <LinearLayout 
     android:id="@+id/horizontalLinear" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 
     <TextView 
      android:id="@+id/textView1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="TextView" /> 
     <TextView 
      android:id="@+id/textView2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="TextView" /> 
    </LinearLayout> 
</LinearLayout> 
相關問題