不客气,希望能帮到您。如果您还有其他问题,欢迎随时咨询。

根据你提供的代码,存在以下问题:

  1. bjhzView 类中定义了两个类名相同的类,需要删除第一行的 'public class bjhzView {'。
  2. bjhzView 类需要继承自 View 类,因此需要修改第二行为 'public class bjhzView extends View {'。
  3. MainActivity 中需要将 'setContentView(new bjhzView(this));' 的注释取消,否则无法显示自定义 View。
  4. 在 bjhzView 的 onDraw 方法中,应先调用父类的 onDraw 方法,再进行自定义绘制。 以下是修改后的代码: XML 文件:
<LinearLayout     xmlns:android='http://schemas.android.com/apk/res/android'     android:layout_width='match_parent'     android:layout_height='match_parent'     android:gravity='center'>      <com.myyg.bjhzView         android:layout_width='200dp'         android:layout_height='200dp'/> </LinearLayout>

bjhzView.java 文件:

package com.myyg;
import android.content.*;
import android.graphics.*;
import android.view.*;
public class bjhzView extends View {
    public bjhzView(Context context) {
        super(context);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint a = new Paint();
        a.setColor(Color.RED);
        canvas.drawCircle(100, 100, 50, a);
    }
}

MainActivity.java 文件:

package com.example.myapplication;
import android.app.*;
import android.os.*;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new bjhzView(this));
    }
}
Android 自定义 View 代码检查及优化

原文地址: https://www.cveoy.top/t/topic/k43g 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录