3

这应该很容易做到,但不知何故,经过大约 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);
}
}

但是,textbutton子视图为空。任何想法?(XML 非常简单,没有任何花哨的编辑,我只是​​从 Eclipse 工具栏中抓取了一个 TextView 和一个 Button 并投入其中。)

4

1 回答 1

7

好的,所以我自己的问题的答案是:(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);
    }
}
于 2012-05-28T10:24:14.490 回答