如何在android中设置布局中的customview

如何在android中设置布局中的customview,android,Android,这里是活动,在此活动中仅创建了一个自定义视图 public class MainActivity extends Activity { MyCustomDrawableView myCustomDrawableView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); myCustomDrawableView = new MyC

这里是活动,在此活动中仅创建了一个自定义视图

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);
    }
    }
}
public MyCustomDrawableView(Context context, AttributeSet st) {
    super(context, st);
    // Do other initial tasks, like you did into MyCustomDrawableView(Context context).
}
然后在布局中创建customview,如下所示

<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" />
请帮助

更好的方法是为自定义视图使用单独的类(不应是内部类)

对于您当前的问题,请尝试使用

<com.mobiloitte.sampleapp.MainActivity$MyCustomDrawableView

将MyCustomDrawableView保存在单独的类文件中为什么是静态的?我从未将静态类用于视图。@StephaneMathis将其删除。如果该视图仅用于相同的活动,那么就可以了。但是,如果在另一个活动中使用视图的内部版本,它需要外部(活动类)的实例,因此在这种情况下最好使用静态。这仅适用于内部版本。@PankajKumar错误:解析XML时出错:格式不正确(无效令牌),您的answer@Srikanth然后您必须编写单独的视图类,而不是内部类。@PankajKumar非常感谢您的时间…:-)
public MyCustomDrawableView(Context context, AttributeSet st) {
    super(context, st);
    // Do other initial tasks, like you did into MyCustomDrawableView(Context context).
}