Android按钮onClick XML无法正常工作

时间:2011-04-13 00:10:08

标签: android button onclick

Eclipse不喜欢我的addLifeForP1方法,该方法由PlusLifeForP1Button的onClick调用。它说下面的方法调用:          - 令牌上的语法错误“(”,;;      - 令牌上的语法错误“)”,;预期      - void是变量的无效类型 如果你能搞清楚,请告诉我!

public class ActivityTab1 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content1layout);

        Resources res = getResources();
        ImageButton plusLifeButtonP1 = (ImageButton) findViewById(R.id.PlusLifeForP1);
        TextView lifeViewP1 = (TextView) findViewById(R.id.LifeForP1);

        public void addLifeForP1(View view) {
            CharSequence sequence = lifeViewP1.getText();
            String string = sequence.toString();
            int lifeTotal = Integer.parseInt(string);
            lifeTotal++;
            lifeViewP1.setText(lifeTotal);      
        }
    }
    }

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:label="@+id/LifeForP1"
        android:text="20"
        android:color="#990000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="90px"
        android:layout_y="0px"
        android:textSize="250px"
    />

    <ImageButton
        android:label="@+id/PlusLifeForP1"
        android:background="#ff000000"
        android:src="@drawable/plus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="140px"
        android:layout_y="280px"
        android:onClick="addLifeForP1"
    />

    <ImageButton
        android:label="@+id/MinusLifeForP1"
        android:background="#ff000000"
        android:src="@drawable/minus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_x="245px"
        android:layout_y="280px"
    />

</AbsoluteLayout>

2 个答案:

答案 0 :(得分:3)

您在onCreate方法的末尾缺少结束括号。

答案 1 :(得分:2)

在onCreate函数外粘贴addLifeForP1。这将解决问题。

public class ActivityTab1 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedIn`enter code here`stanceState);
        setContentView(R.layout.content1layout);

        Resources res = getResources();
        ImageButton plusLifeButtonP1 = (ImageButton) findViewById(R.id.PlusLifeForP1);
        TextView lifeViewP1 = (TextView) findViewById(R.id.LifeForP1);
    }

    public void addLifeForP1(View view) {
        CharSequence sequence = lifeViewP1.getText();
        String string = sequence.toString();
        int lifeTotal = Integer.parseInt(string);
        lifeTotal++;
        lifeViewP1.setText(lifeTotal);      
    }
}