这应该很容易做到,但不知何故在搜索了大约 15 分钟后我仍然无法得到答案:
我想制作一个结合了 TextView 和 Button 的自定义 Android View,再加上一些自定义的行为/方法,假设当我单击按钮时,它应该将 TextView 更改为“Hello, world!”。
我知道我必须扩展 View 类,并在 XML 中设计布局,然后施展魔法将两者联系起来。你能告诉我魔法是什么吗?我知道如何在 Activity 中执行此操作,但不知道如何在自定义 View 中执行此操作。
已编辑 好的,所以我发现我需要使用 Inflater 来使用布局中定义的 subview 来扩展我的类。这是我得到的:
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);
}
}
但是,text
和 button
subview 为空。任何的想法? (XML 非常简单,没有任何花哨的编辑,我只是从 eclipse 工具栏中抓取一个 TextView 和一个 Button 并放入。)
最佳答案
好的,所以我自己的问题的答案是:(i) 去吃晚饭,(ii) 扩展 LinearLayout
而不是 View
,这使它成为一个 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);
}
}
关于Android自定义View(TextView+Button+一些自定义行为)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10781218/