2013-03-22 54 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