有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在声明按钮时仿真程序中出现错误

当我在MainActivity中声明按钮时。java,我在emulator中不幸遇到错误

但是当我评论按钮声明时,没有错误

这是主要的活动。java代码:

package com.MalekAlrwily.multiplication;

import 安卓.os.Bundle;
import 安卓.view.View;
import 安卓.view.View.OnClickListener;
import 安卓.widget.Button;
import 安卓.app.Activity;
import 安卓.content.Intent;

public class MainActivity extends Activity {

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

    final Button btn = (Button)findViewById(R.id.btn_start) ;
}



}

这是主要的。xml代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:background="@drawable/main2" >

<ImageButton
    安卓:id="@+id/btn_start"
    安卓:layout_width="wrap_content"
    安卓:layout_height="wrap_content"
    安卓:layout_alignParentLeft="true"
    安卓:layout_alignParentTop="true"
    安卓:background="@安卓:color/transparent"
    安卓:contentDescription="@安卓:string/ok"
    安卓:src="@drawable/sun" />

</RelativeLayout>

请帮忙

提前谢谢


共 (4) 个答案

  1. # 1 楼答案

    这是因为,您在xml中声明为ImageButton,并动态地声明Button

    应该是:

    final ImageButton btn = (ImageButton) findViewById(R.id.btn_start) ;
    
  2. # 2 楼答案

    您在java文件中声明了Button,而不是ImageButton

    声明如下:

    final ImageButton btn = (ImageButton)findViewById(R.id.btn_start) ;
    
  3. # 3 楼答案

    这是因为你试图将ImageButton加载为Button

    你应该使用

    final ImageButton btn = (ImageButton)findViewById(R.id.btn_start) ;
    
  4. # 4 楼答案

    这是布局中的ImageButton,因此您也应该在活动中使用ImageButton

    final Button btn = (Button)findViewById(R.id.btn_start) ;
    

    这应该是

    final ImageButton btn = (ImageButton) findViewById(R.id.btn_start) ;