需要帮助onclick

时间:2014-09-22 19:42:55

标签: java android xml android-layout

我正在构建一个Android应用程序,基本上我希望它可以计算屏幕上的点击(任何地方)。现在我尝试将RelativeLayout置于android:clickable="true"和我的1 TextView相同,但当我尝试启动Activity应用程序崩溃时。我希望它显示时间,让我们说30秒,然后计算这30秒的水龙头。

XML

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.orion.peky.thetapgame.Game">       

         <TextView
             android:text="Tap to start"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_centerVertical="true"
             android:layout_centerHorizontal="true"
             android:textSize="50dp"
             android:textColor="#FFFFFFFF"
             android:id="@+id/tekst" />

     </RelativeLayout>

活动

 MAIN package com.orion.peky.thetapgame;

 import android.app.Activity;
 import android.os.Bundle; 
 import android.view.Menu; 
 import android.view.MenuItem; 
 import android.view.View;
 import android.widget.TextView;



 public class Game extends Activity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_game);
     }
     TextView tekst=(TextView)findViewById(R.id.tekst);
     int brojac=0;

     public void broji(View view){
         brojac=brojac+1;
         tekst.setText("Tapped "+brojac+" times");
     } }

1 个答案:

答案 0 :(得分:0)

onCreate()方法之外的这行代码出错:

 TextView tekst=(TextView)findViewById(R.id.tekst);
 int brojac=0;

放入onCreate()方法,将TextView tekst声明为Class变量,然后您也可以在broji()方法中使用它:

public class Game extends Activity {

private TextView tekst;
private int brojac=0;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_game);
      tekst=(TextView)findViewById(R.id.tekst);
     }

     public void broji(View view){
         brojac=brojac+1;
         tekst.setText("Tapped "+brojac+" times");
     } 
}
相关问题