无法从Activity或类调用自定义视图(canvasview)的方法

sro*_*ero 1 java android

我无法从设置布局(包括视图)的Activity中调用自定义视图("canvasview")的方法.我甚至无法从活动中调用canvasview的"getters".

另外,我将视图传递给自定义类(不扩展Activity),我也不能从我的自定义类调用canvasview的方法.

我不确定我做错了什么......

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();
    (...)
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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;
    }    
Run Code Online (Sandbox Code Playgroud)

我对此很困惑:?

我还有另一个类(它没有扩展"Activity"),它在构造函数中接收对canvasview的引用,也无法"解析"它:

谢谢,对不起,如果这个问题太明显了,我就是从Java开始,那些东西让我很困惑......

编辑:

在床上(凌晨03:00)考虑一下,我注意到Eclipse将该行标记为错误,因为View对象实际上没有方法get_canvaswidth().只有子"CanvasView"方法才有它.因此,我的问题可以用upcast解决:

int w = ((CanvasView) canvasview).get_canvaswidth();
Run Code Online (Sandbox Code Playgroud)

我的意思是我收到一个视图作为参数,但是因为我现在它真的是一个视图孩子,我应该能够使用upcast来调用"child's"方法.现在eclipse不会产生错误但是 w和h总是报告0: - ?.我还测试了不使用upcast,如答案中所建议的,并且在调用中发送和接收CanvasView对象,我也得到0:

j__*_*__m 5

private View canvasview;
Run Code Online (Sandbox Code Playgroud)

无论存储在何处,canvasview您只能调用由变量类型定义的方法.你需要改变这一行.

private CanvasView canvasview;
Run Code Online (Sandbox Code Playgroud)