我无法从设置包括视图在内的布局的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();
(...)
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;
}
我对此非常困惑:?
我还有另一个类(它没有扩展&#34; Activity&#34;)在构造函数中接收对canvasview的引用,也无法解析&#34;它:?
谢谢,对不起,如果问题太明显了,我是从Java开始的,这些事情对我来说很混乱......
修改
在床上(凌晨03:00),考虑到它,我注意到Eclipse将该行标记为错误,因为View对象实际上没有方法get_canvaswidth()。只有孩子&#34; CanvasView&#34;方法有它。因此,我的问题可以通过 upcast :
来解决int w = ((CanvasView) canvasview).get_canvaswidth();
我的意思是我收到一个视图作为参数,但是因为我现在它真的是一个视角孩子,我应该可以使用upcast来调用&#34; child&#39; s&#34;方法。现在eclipse不会产生错误但是 w并且h总是报告0: - ? 。我还测试了不使用upcast,如答案中所建议的,并且在调用中发送和接收CanvasView对象,我也得到0:?
答案 0 :(得分:5)
private View canvasview;
无论canvasview
中存储的是什么,您都只能调用变量类型定义的方法。你需要改变这一行。
private CanvasView canvasview;