【问题标题】:Android custom View (TextView+Button+some customized behaviors)?Android自定义View(TextView+Button+一些自定义行为)?
【发布时间】:2012-05-28 07:59:02
【问题描述】:

这应该很容易做到,但不知何故,经过大约 15 分钟的搜索,我仍然无法得到答案:

我想制作一个结合 TextView 和 Button 的自定义 Android View,以及一些自定义的行为/方法,假设当我单击按钮时,它应该将 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 并投入其中。)

【问题讨论】:

    标签: android button view textview


    【解决方案1】:

    好的,所以我自己的问题的答案是:(i)去吃饭,(ii)扩展LinearLayout而不是View,这使它成为ViewGroup,因此可以传递到@987654324 @ 方法,但不必重写 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);
        }
    }
    

    【讨论】:

    • 我也想要这个功能,但没有搞清楚。你能显示 R.layout.myview 吗?
    猜你喜欢
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2023-03-15
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多