我觉得我曾经知道如何做到这一点,但现在却一片空白。我有一个扩展自View的类(Card
),并且我用XML为它编写了一个布局。我想做的是将Card
的视图设置为构造函数中的XML视图,以便我可以使用Card
中的方法来设置TextView
等内容。有什么建议?下面是代码:
Card.java:
(我在那里使用了View.inflate(context, R.layout.card_layout, null);
作为我想要做的事情的示例,但它不起作用。我基本上希望该类成为 View 的接口,并且为此我需要以某种方式分配 XML 布局给 View。我是否要使用类似于 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
,但后来觉得这是个愚蠢的想法。在看到这条评论后,我尝试了一下,结果完美运行!非常感谢! - user766650