Android custom View (TextView+Button+some customiz

2020-07-23 06:40发布

问题:

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

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!".

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

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.)

回答1:

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