我已经遇到了一个问题,我现在已经想要解决一个星期了。我正在尝试使用onDraw
类中的View
方法。问题是,在我的Java
类中,我已经导入了一些东西,我不知道如何获得View
类方法,因为Java dosent允许扩展多个类。我一直在寻找其他帖子,我已尝试过解决方案,但在 my senario 中,几乎所有解决方案都不起作用。任何其他解决方案?
Java类:
import android.graphics.Canvas;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity /*Cant get rid of this import*/ {
//Cant import View because something is already imported
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tw = findViewById(R.id.text2);
//Tried using View.onDraw(canvas), gives me error
}
//Will not work
@Override
public void onDraw(Canvas canvas){
super.onDraw(canvas);
}
}
答案 0 :(得分:1)
如果您愿意,请查看并接受建议:)
/**
* Created by Prafulla Malviya on 2/25/2018.
* Time : 2.38 AM India
*/
public class DemoActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
//init();
//initView();
}
}
package com.abhaya_foundation.abhayango;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
/**
* Created by Prafulla Malviya on 2/25/2018.
* Time : 2.38 AM India
*/
public class MyView extends View {
private Paint paint;
public MyView(Context context) {
super(context);
// create the Paint and set its color
paint = new Paint();
paint.setColor(Color.GRAY);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLUE);
canvas.drawCircle(200, 200, 100, paint);
}
}
或者你可以添加
<FrameLayout
android:orientation="vertical"
android:id="@+id/view_1"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
在您的活动xml中,将MyView实例传递给他们。
MyView myView = new MyView(this);
FrameLayout view = (FrameLayout)findViewById(R.id.view_1);
view.addView(myView);