Android的自定义视图(TextView的+按键+一些定制行为)? [英] Android custom View (TextView+Button+some customized behaviors)?

查看:95
本文介绍了Android的自定义视图(TextView的+按键+一些定制行为)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是很容易做到的,但不知何故后大约15分钟时间来寻找我仍然无法得到答案:

This should be very easy to do, but somehow after some 15 minutes searching I still can't get the answer:

我想打一个定制的Andr​​oid视图结合一个TextView和一个Button,再加上一些自定义的行为/方法,比方说,当我按一下按钮就应该改变的TextView为你好,世界!。

I want to make a custom Android View combining a TextView and a Button, plus some customized behaviors/methods, let's say when I click the button it should change the TextView to "Hello, world!".

我知道,我将不得不扩展视图类,设计布局在一个XML,然后做一些魔法来连接两个。你能告诉我神奇的是什么呢?我知道如何做到这一点在活动,而不是在一个自定义的视图。

I know that I'll have to extends the View class, and design the layout in a XML, then do some magic to link the two. Could you tell me what the magic is? I know how to do this in an Activity, but not in a custom View.

EDITED 好了,我发现我需要用一个充气用在布局中定义的子视图夸大我的课。这是我得到的答案:

EDITED Ok, so I found out I need to use a Inflater to inflate my class with the child views defined in a layout. Here's what I got:

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);
}
}

不过,文本按钮子的观点是空。任何想法? (XML是没有任何花哨的编辑很简单,我只是抓住一个TextView从Eclipse工具栏上一个按钮,扔在)

However, the text and button child views were null. Any idea? (The XML is very simple without any fancy edit, i just grabbed a TextView and a Button from the eclipse toolbar and throw in.)

推荐答案

好了,回答我的问题是:(一)去找吃饭,(二)扩展的LinearLayout 查看>,这使得它的ViewGroup ,因此可以传递到膨胀(...)方法,但不必重写 onLayout(...)方法。更新后的code将是:

Ok, so the answer to my own question is: (i) go get dinner, (ii) extends LinearLayout instead of View, this makes it a ViewGroup and thus can be passed into the inflate(...) method but don't have to override the onLayout(...) method. The updated code would be:

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的自定义视图(TextView的+按键+一些定制行为)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆