Subclass Button with Android : lots of errors

2019-03-06 11:45发布

问题:

I tried to subclass Button , but I have a lot of errors when launching my project. Could you have a look and tell me how to fix this? (I've got maybe 50 errors coming up)

package my.project.name;

import android[...]

public class MyButton extends Button {

    public MyButton(){
        super(null);
    }

    public MyButton(Context context){
        super(context);
    }

    public MyButton(Context context, AttributeSet attrs){
        super(context, attrs);
    }

    public MyButton(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
    }

    @Override 
    protected void onDraw(Canvas canvasObject) {
        super.onDraw(canvasObject);
        int x = 100;
        int y = 100;
        int width = 80;
        int height = 200;
        Paint thePaint = new Paint();   
        thePaint.setColor(Color.WHITE);
        RectF rectangle1 = new RectF(x,y,x+width,y+height);
        canvasObject.drawRoundRect(rectangle1, 10.0f, 10.0f, thePaint);   
    }

}

the main class :

package my.project.name;

import android.app.Activity;
import android.os.Bundle;

public class MyProjectActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

and the xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <MyButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/myb"
        android:tag="tag"
         />

</LinearLayout>

EDIT: actually, the rectangle does not show up, the subclass works, because i've got no error, but the rectangle is just not visible, even with the background to "@null"...

Thanks a lot

回答1:

rename

<MyButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myb"
    android:tag="tag"
     />

to a fully qualified Namespace

<namespace.from.button.MyButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myb"
    android:tag="tag"
     />


回答2:

Using the fully-qualified name for the element in the XML layout does not work if your Button subclass is an inner class. If this is the case, you need to add a class attribute and use the generic view for the element name.

<view
    class="my.project.name.MyProjectActivity$MyButton"
    ...

http://developer.android.com/guide/topics/ui/custom-components.html