1

LinearLayoutプログラムでいくつかに追加したいと思いTextViewsます。そして使いたいLayoutInflater。私は私のアクティビティレイアウトxmlファイルに持っています:

<LinearLayout
     android:id="@+id/linear_layout"
     android:layout_width="wrap_content"
     android:layout_height="fill_parent"
     android:orientation="vertical"
     />

以下のようなアクティビティコードを書きました。

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);
textView.setText("Some text");
linearLayout.addView(textView);

私のscale.xmlファイルは次のようになります。

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_weight="1"
     android:layout_marginLeft="50dp"
     android:layout_marginRight="50dp"  
     android:drawableTop="@drawable/unit"
     />

TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);で、以下のような致命的な例外があります。

 java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MyActivity}: 
 java.lang.ClassCastException: android.widget.LinearLayout
 Caused by: java.lang.ClassCastException: android.widget.LinearLayout

問題のある行をnullに置き換えるとlinearLayout、例外はありませんが、私のandroid:layout_marginLeftとは無視され、追加されたTextViewの周りにマージンが表示されません。android:layout_marginRightscale.xml

ExpandableListView にヘッダー ビューを追加するときに Android: ClassCastExceptionという質問が見つかりましたが、私の場合、インフレータを使用する最初の行に例外があります。

4

1 に答える 1

3

linearLayoutの呼び出しでルートビュー()を指定するinflater.inflate()と、拡張されたビューがビュー階層に自動的に追加されます。したがって、を呼び出す必要はありませんaddView。また、お気づきのとおり、返されるビューは階層のルートビュー(a LinearLayout)です。それ自体への参照を取得するには、次のコマンドで取得TextViewできます。

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().
    getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
inflater.inflate(R.layout.scale, linearLayout, true);
TextView textView = (TextView) linearLayout.getChildAt(
    linearLayout.getChildCount()-1);
textView.setText("Some text");

ビューandroid:idにscale.xmlの属性を指定する場合は、次のコマンドでビューを取得できます。

TextView textView = (TextView) linearLayout.findViewById(R.id.text_id);
于 2012-03-11T21:17:38.483 に答える