2013-12-18 21 views
5

私は以下の構造のabc.xmlを持っています。Android:ネストされたレイアウトで動的にビューを追加する

<ScrollView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
<RelativeView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 
    <LinearLayout 
    android:id="@+id/linear" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    > 
    </LinearLayout> 
</RelativeLayout> 
</ScrollView> 

線形レイアウトにtextviewsを動的に追加したいとします。以下は私のコードです。私は間違いはありませんが、私は望みの結果を得ていません。

LayoutInflater Inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View view = Inflater.inflate(R.layout.abc, null); 

LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear); 

     TextView Tag = new TextView(getActivity()); 
     Tag.setText("textString"); 
     Tag.setBackgroundResource(R.color.bg_color); 
     Tag.setTextAppearance(getActivity(), R.style.SmallFont); 
     layout.addView(Tag); 
+0

なぜRelativeLayoutを使用していますか? –

+0

私は相対レイアウトで他のビューを持っているだけでなく、textviewsとbuttonviews – Shah

答えて

6

あなたのXMLはテキストビューを追加する

<ScrollView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <LinearLayout 
    android:id="@+id/linear" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    > 
    </LinearLayout> 
</LinearLayout> 
</ScrollView> 

とJavaコードでなければなりません

LinearLayout layout = (LinearLayout) view.findViewById(R.id.linear); 
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); 
TextView Tag = new TextView(getActivity()); 
tag.setLayoutParams(params); 
Tag.setText("textString"); 
Tag.setBackgroundResource(R.color.bg_color); 
Tag.setTextAppearance(getActivity(), R.style.SmallFont); 
layout.addView(Tag); 
0

である私は、あなたがまだ答えを見つけたか分からないが、私はちょうど持っていましたこの問題に遭遇し、私は1つの方法を見つけました。 私はあなたが以下のように1ビットのレイアウトを調整する必要があると思う:

<ScrollView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <RelativeView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" > 

      <LinearLayout 
       android:id="@+id/linear" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" > 
      </LinearLayout> 
     </LinearLayout> 

    </RelativeView> 

</ScrollView> 
0

あなたが与えなければならない、idを持つリニアレイアウトに

android:layout_orientation="either horizontal or vertical" 

:線形。

関連する問題