【问题标题】:Need assistance with onclick [duplicate]需要关于 onclick 的帮助 [重复]
【发布时间】:2014-09-22 19:42:54
【问题描述】:

我正在构建一个 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");
     } }

【问题讨论】:

  • 我无法使用它,我的笔记本电脑无法运行仿真程序,我无法在连接到笔记本电脑时在手机上实时运行它...顺便说一句,我删除了 android:clickable="true" 和 android :onclick="broji" 在没有它的情况下运行它...
  • setContentView之后将tekst=(TextView)findViewById(R.id.tekst);移动到Activity的onCreate中

标签: java android xml android-layout


【解决方案1】:

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

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

放入onCreate() 方法中,将TextView tekst 声明为类变量,然后您也可以在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");
     } 
}

【讨论】:

  • 而在这个世界上,没有人可以解释任何事情。确实,您应该因为没有给出任何解释而获得 +1 :)
  • 现在工作我知道我有一个错误但没有注意到它是一个全局变量 xd 谢谢
猜你喜欢
  • 2014-03-11
  • 2014-09-25
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2011-11-12
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
相关资源
最近更新 更多