简体   繁体   中英

How to set customview in layout in android

Here is activity and with in this activity only created one custom view

public class MainActivity extends Activity {
MyCustomDrawableView myCustomDrawableView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     myCustomDrawableView = new MyCustomDrawableView(this);
    setContentView(R.layout.activity_main);
    myCustomDrawableView = (MyCustomDrawableView)findViewById(R.id.hello);
}

public class MyCustomDrawableView extends View {
    private ShapeDrawable myDrawable;

    public MyCustomDrawableView(Context context) {
        super(context);
        int x = 10;
        int y = 10;
        int width = 100;
        int height = 100;

        myDrawable = new ShapeDrawable(new OvalShape());
        myDrawable.getPaint().setColor(0xff74fA23);
        myDrawable.setBounds(x, y, x + width, y + height);
    }

    protected void onDraw(Canvas canvas) {
        myDrawable.draw(canvas);
    }
    }
}

then in layout create customview as follows

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<com.mobiloitte.sampleapp.MainActivity.MyCustomDrawableView
    android:id="@+id/hello"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

here i'm getting class not found exception

10-20 13:00:33.594: E/AndroidRuntime(542): Caused by: java.lang.ClassNotFoundException: com.mobiloitte.sampleapp.MainActivity.MyCustomDrawableView

pls help

Better is to use separate class (should not be an inner class) for custom view.

For your current problem, try with

<com.mobiloitte.sampleapp.MainActivity$MyCustomDrawableView

Update for current issue android.view.InflateException

You need to add one more constructor for your custom view

public MyCustomDrawableView(Context context, AttributeSet st) {
    super(context, st);
    // Do other initial tasks, like you did into MyCustomDrawableView(Context context).
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM