我正试图在我的MyActivity中获得一个来自视图MyView的int。在我的活动中,我有以下内容:
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中我会犯以下错误:
致命异常:主进程: com.example.ex,PID: 8035 java.lang.ClassCastException: android.app.Application不能在com.example.ex.myView上转换为com.example.ex.myView$GetCallBack。(myView.java:49)
我知道错误与上下文有关,但我仍然没有找到纠正错误的方法,
任何想法都会很感激的!)
发布于 2016-04-15 14:25:46
您已经在interface中实现了myActivity,但是您正在传递应用程序上下文。这就是为什么你要得到ClassCastException。传递myActivity.this,所以尝试如下:
surface.addView(new MyView(MyActivity.this);https://stackoverflow.com/questions/36649811
复制相似问题