rob*_*y12 7 android android-layout android-view
我觉得好像我曾经知道如何做到这一点,但我现在正在画一个空白.我有一个从View(Card
)扩展的类,我在XML中为它编写了一个布局.我想要做的是Card
在构造函数中将View视图设置为XML视图,因此我可以使用方法Card
来设置TextView
s和诸如此类的东西.有什么建议?代码如下:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
Luk*_*rog 10
当前的设置无法实现您想要做的事情.A View
(或它的直接子类)表示单个视图,它没有子视图的概念,您正在尝试做什么.在LayoutInflater
不能用一个简单的使用View
,因为简单的View
类没有方法实际上孩子添加到它(如addView()
方法).
在另一方面,正确的类使用才能够生孩子是ViewGroup
(或直接子类等中的一种LinearLayout
,FrameLayout
它接受增加等)Views
或其他ViewGroups
通过提供给它,addView
方法.最后你的班级应该是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我记得你必须覆盖,onLayout
如果你扩展ViewGroup
,所以相反(并且由于你的布局文件),你应该看看扩展LinearLayout
并用标签替换LinearLayout
xml布局merge
.
归档时间: |
|
查看次数: |
5740 次 |
最近记录: |