2016-04-15 56 views
0

我試圖從視圖MyView中獲取我的MyActivityint。在我的活動我有以下幾點:活動和視圖之間的接口的實現錯誤

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中我得到以下錯誤:

致命例外:main 進程:com.example.ex,PID:8035 java.lang.ClassCastException:android.app.Appli陽離子不能被轉換 到com.example.ex.myView $ GetCallBack 在com.example.ex.myView。(myView.java:49)

我知道錯誤與環境相關的,但我還沒有找到一種方法來糾正它,

任何想法將非常感激! :)

回答

1

您已在myActivity中實施interface,但您正在傳遞應用程序上下文。這就是爲什麼你得到ClassCastException。通過myActivity.this,所以嘗試這樣的:

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

改變了資本;) – Alvaro

+0

'myView'也應改爲'MyView'。 –