gpt4 book ai didi

java - Activity和View之间的接口(interface)实现错误

转载 作者:行者123 更新时间:2023-12-01 10:03:16 25 4
gpt4 key购买 nike

我正在尝试从 View MyView 获取MyActivity 中的int。在我的 Activity 中,我有以下内容:

public class MyActivity extends AppCompatActivity implements MyView.GetCallBack {

final MyActivity context = this;
private AsyncTask<Void, Void, Void> task;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_second_act);

task = new myTask();
task.execute();

}

@Override
public void onPercentageReceived(int msg){
// you have got your msg here.
}

public class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
}
@Override
protected void onPostExecute(Void result) {

LinearLayout surface = (LinearLayout) findViewById(R.id.surfaceView);
surface.addView(new MyView(getApplicationContext()));
surface.setBackgroundColor(Color.BLACK);
}

}

现在MyView包含以下代码:

public class MyView extends View {
final MyView context = this;
private GetCallBack callback;
// Constructor
public PlacingBoxView(Context context) {
super(context);
callback = (GetCallBack) context;
}

@Override
protected void onDraw(Canvas canvas) {
dataPercentage(Percentage);
}

public void dataPercentage(int Percentage){
callback.onPercentageReceived(Percentage);
}


public interface GetCallBack{
void onPercentageReceived(int msg);
}

我可以毫无问题地编译代码,但在 LogCat 中出现以下错误:

FATAL EXCEPTION: main Process: com.example.ex, PID: 8035 java.lang.ClassCastException: android.app.Application cannot be cast to com.example.ex.myView$GetCallBack at com.example.ex.myView.(myView.java:49)

我知道错误与上下文有关,但我仍然没有找到纠正它的方法,

任何想法都会非常感激! :)

最佳答案

您已在 myActivity 中实现了接口(interface),但您正在传递应用程序上下文。这就是为什么您会收到ClassCastException。传递myActivity.this,所以尝试这样:

surface.addView(new MyView(MyActivity.this);

关于java - Activity和View之间的接口(interface)实现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36649811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com