我感觉好像我曾经知道如何做到这一点,但我现在是一片空白。我有一个从 View (Card
) 扩展的类,我用 XML 为它编写了一个布局。我想做的是将 Card
的 View 设置为构造函数中的 XML View ,这样我就可以使用 Card
中的方法来设置 TextView
s等等。有什么建议么?代码如下:
卡片.java:
(我有 View.inflate(context, R.layout.card_layout, null);
作为我想做的事情的例子,但它不起作用。我基本上希望类成为接口(interface)对于 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>
最佳答案
您尝试执行的操作在当前设置下是不可能的。 View
(或其直接子类)代表一个单一 View ,它没有 subview 的概念,也就是您要尝试执行的操作。 LayoutInflater
不能与简单的 View
一起使用,因为简单的 View
类没有将子项实际添加到其中的方法(类似于 addView()
方法)。
另一方面,能够拥有 child 的正确类是 ViewGroup
(或直接子类之一,如 LinearLayout
、FrameLayout
等)接受添加 Views
或其他 ViewGroups
,通过提供 addView
方法。最后你的类(class)应该是:
public class Card extends ViewGroup {
TextView tv;
public Card(Context context) {
super(context);
View.inflate(context, R.layout.card_layout, this);
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, this);
tv = (TextView) findViewById(R.id.tv);
}
public Card(Context context, AttributeSet attrs) {
super(context, attrs);
View.inflate(context, R.layout.card_layout, this);
tv = (TextView) findViewById(R.id.tv);
}
public void setText(String text) {
tv.setText(text);
}
}
如果我记得如果你扩展 ViewGroup
你必须重写 onLayout
,那么你应该考虑扩展 LinearLayout
并将 xml 布局中的 LinearLayout
替换为 merge
标记。
关于android - 使用 XML 布局作为 View 子类的 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117323/