2
私は、レイアウトに追加したい化合物成分Box
を作成しました。 Box
のxml:レイアウトコンパウンドコンポーネントにプログラムでAndroidを追加する方法は?
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayoutForBlock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" android:background="@drawable/screen_background" android:layout_marginLeft="5dp" android:layout_marginTop="5dp">
<ImageButton
android:id="@+id/imageButtonContent"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:scaleType="fitCenter"
android:src="@drawable/beach_bed" android:background="@drawable/buttonbackground" android:clickable="true" android:layout_margin="5dp" android:contentDescription="@string/sample_text"/>
<TextView
android:id="@+id/textViewContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/sample_text"
android:textColor="@color/deep_blue" android:layout_margin="5dp"/>
</LinearLayout>
</merge>
Box
クラス:
<com.mypackage.alexey.Box
android:id="@+id/mybox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
問題は、私がしたいことです:
public class Box extends LinearLayout {
private TextView textContent;
private ImageView imageContent;
public Box(Context context, AttributeSet attrs) {
super(context, attrs);
((Activity)getContext()).getLayoutInflater().inflate(R.layout.box, this);
setupViewItems();
}
private void setupViewItems() {
textContent = (TextView) findViewById(R.id.textViewContent);
imageContent = (ImageView) findViewById(R.id.imageButtonContent);
}
public void setTextContent(String text) {
this.textContent.setText(text);
}
public void setImageContent(String tag) {
this.imageContent.setContentDescription(tag);
}
}
すべては私のようなメインのxmlファイルにBox
を追加した場合に動作多くのボックスをプログラムで作成する:Box mybox= new Box();
。どうやってするの?
答えていただきありがとうございますが、値を割り当てようとすると問題が発生します:theBox.setTextContent( "New content");私は例外(NullPointerException)を取得します – Alex
@alexeyあなたが 'Box'クラスをインスタンス化し、' theBox'が有効なオブジェクトであることは 'NullPointerException'がおそらく' textContent'が 'null'から来ることを意味します)。 'onFinishInflate'への呼び出しがどのように行われているのかわかりませんが(xmlレイアウトではうまくいくと思います)、' R.layout.box'ファイルを展開してビューを設定するコードを移動することをお勧めします( 'setupViewItems()')を単純な 'Context'をとり、もう一度やり直してください。 'inflate(R.layout.box、this、true);' – Luksprog
あなたが提案したように、今は動作します、ありがとうございます! – Alex