pck*_*ben 3 android view button textview
这应该很容易做到,但不知怎的,经过大约15分钟的搜索,我仍然无法得到答案:
我想制作一个结合TextView和Button的自定义Android视图,以及一些自定义的行为/方法,让我们说当我点击按钮时它应该将TextView更改为"Hello,world!".
我知道我必须扩展View类,并在XML中设计布局,然后做一些魔术来链接这两者.你能告诉我魔术是什么吗?我知道如何在Activity中执行此操作,但不在自定义视图中执行此操作.
编辑 好了,所以我发现我需要使用Inflater来通过布局中定义的子视图来扩充我的类.这是我得到的:
public class MyView extends View {
private TextView text;
private Button button;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
View.inflate(context, R.layout.myview, null);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,text和button子视图为空.任何的想法?(XML非常简单,没有任何花哨的编辑,我只是从eclipse工具栏中抓取一个TextView和一个Button并投入.)
好吧,所以我自己的问题的答案是:(i)去吃饭,(ii)延伸LinearLayout而不是View,这使它成为a ViewGroup,因此可以传递给inflate(...)方法但不必覆盖onLayout(...)方法.更新的代码将是:
public class MyView extends LinearLayout {
private TextView text;
private Button button;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
View.inflate(context, R.layout.myview, this);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5043 次 |
| 最近记录: |