我感覺好像我曾經知道如何做到這一點,但我目前正在畫空白。我有一個從View(Card
)延伸出來的類,我用XML編寫了它的佈局。我想要做的是將Card
的視圖設置爲構造函數中的XML視圖,因此我可以使用Card
中的方法設置TextView
s以及什麼。有什麼建議麼?下面的代碼:使用XML佈局作爲View子類的視圖?
Card.java: (我有View.inflate(context, R.layout.card_layout, null);
那裏的是我想要做的例子,但它不工作我基本上希望類是視圖的接口,爲了做我需要以某種方式分配XML佈局視圖。難道我用的東西沿着setContentView(View view)
線?還有就是在View
類中沒有這樣的方法,但有類似的東西?)
public class Card extends View {
TextView tv;
public Card(Context context) {
super(context);
View.inflate(context, R.layout.card_layout, null);
tv = (TextView) findViewById(R.id.tv);
}
public Card(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
View.inflate(context, R.layout.card_layout, null);
tv = (TextView) findViewById(R.id.tv);
}
public Card(Context context, AttributeSet attrs) {
super(context, attrs);
View.inflate(context, R.layout.card_layout, null);
tv = (TextView) findViewById(R.id.tv);
}
public void setText(String text) {
tv.setText(text);
}
}
card_layout。 xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="336dp"
android:layout_height="280dp"
android:layout_gravity="center"
android:background="@drawable/card_bg"
android:orientation="vertical" >
<TextView
android:id="@+id/tv"
android:layout_height="fill_parent"
android:layout_width="wrap_content"
android:textSize="24dp"
/>
</LinearLayout>
我想過讓我的課程延伸'LinearLayout',然後認爲這是一個愚蠢的想法。我看到這個評論後嘗試了它,它完美的工作!非常感謝你! – roboguy12