2013-03-22 52 views
1

調用自定義視圖(canvasview)的方法我無法從設置佈局(包括視圖)的Activity中調用自定義視圖(「canvasview」)的方法。我甚至無法從活動中調用canvasview的「getters」。另外,我將視圖傳遞給一個自定義類(它不擴展Activity),並且我也無法從我的自定義類中調用canvasview的方法。無法從Activity或類

我不知道我做錯了什麼......

GameActivity.java:

public class GameActivity extends Activity implements OnClickListener 
{ 

    private View canvasview; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.game_layout); 

     canvasview = (View) findViewById(R.id.canvasview); 

     // Eclipse displays ERROR con those 2 method calls: 
     int w = canvasview.get_canvaswidth(); 
     int h = canvasview.get_canvasheight(); 
    (...) 

game_layout.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/LinearLayout2" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    tools:context=".GameActivity" > 

    (...) 

    <com.example.test.CanvasView 
     android:id="@+id/canvasview" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" /> 

</LinearLayout> 

CanvasView .java:

public class CanvasView extends View 
{ 
    private Context context; 
    private View view; 
    private int canvaswidth; 
    private int canvasheight; 

    public CanvasView(Context context, AttributeSet attrs) 
    { 
     super(context, attrs); 
     this.context = context; 
     this.view = this; 
    } 


    @Override 
    protected void onSizeChanged(int width, int height, 
           int old_width, int old_height) 
    { 
     this.canvaswidth = width; 
     this.canvasheight = height; 
     super.onSizeChanged(width, height, old_width, old_height); 
    } 

    public int get_canvaswidth() 
    { 
     return this.canvaswidth; 
    } 

    public int get_canvasheight() 
    { 
     return this.canvasheight; 
    }  

我很困惑這個:?

我還有另一個類(它不擴展「活動」),它在構造函數中接收對canvasview的引用,並且也無法「解析」它:?

謝謝,對不起,如果這個問題太明顯了,我開始使用Java和這種事情是相當混亂給我...

編輯:

雖然在牀(03 :00AM),思考它,我注意到Eclipse將該行標記爲錯誤,因爲View對象實際上並沒有方法get_canvaswidth()。只有孩子「CanvasView」方法有它。因此,我的問題可以用向上轉型解決:

int w = ((CanvasView) canvasview).get_canvaswidth(); 

我的意思是我收到一個視圖作爲參數,但我現在真的是一個視圖的孩子,我應該能夠使用上溯造型叫「孩子的「 方法。現在eclipse不會產生錯誤但是 w和h總是報告0: - ? 。我也測試過不使用upcast,正如答案中所建議的那樣,並且在調用中發送和接收CanvasView對象,並且我還爲這兩個參數獲得0。

回答

5
private View canvasview; 

無論存儲在canvasview中的什麼都只能調用由變量類型定義的方法。你需要改變這一行。

private CanvasView canvasview; 
+1

嗨。謝謝回答。是的,你是對的,但有時你不能改變你收到一個View參數。今天晚上大約凌晨3點,當我在牀上睡覺時,我注意到我的問題可以通過upcast來解決:int w =((CanvasView)canvasview).get_canvaswidth();我的意思是我收到一個視圖作爲參數,但因爲我現在真的是一個視圖孩子,我應該可以使用upcast來調用「孩子」的方法。現在eclipse不會產生錯誤,但w和h總是報告0: - ? 。我已經測試過在調用中不使用upcast併發送和接收CanvasView對象,並且我也爲這兩個參數獲得0。 – sromero 2013-03-23 06:26:28

+0

接受,但它並不是真的需要...只是上傳就足以得到一個有效的參考...無論如何是技術上正確的,並允許解決問題,所以......謝謝! – sromero 2013-03-23 12:18:12