java - android studio,无法识别按钮对象,

标签 java android object button

导入View和Button之后。 我为 Button 创建了一个对象,在本例中为“thomasButton”。

但错误指出字段“thomasButton”未被使用,即使我在下一行调用了它。

一段时间后,我发现把这个字段放在另一个scope中是可以识别的。像这样,但程序仍然无法运行(启动时崩溃)。你们知道为按钮设置 OnLongClickListener 的正确方法是什么吗?

package com.example.thoma.event;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

public void displayMessage(View v){
    TextView thomasText = (TextView)findViewById(R.id.txt_View);
    thomasText.setText(R.string.rsc_Text2);x
}

Button thomasButton = (Button)findViewById(R.id.btn_Change);
// weird but I can only use Button object within an inner scope
{
    thomasButton.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View v) {
            TextView thomasText = (TextView) findViewById(R.id.txt_View);
            thomasText.setText("Artificial");
            // it will return false if long click wasnt long enough
            // and normal click will be called
            return true;
        }
    });
}
}

崩溃:不幸的是,应用已停止

最佳答案

按钮在 onCreate() 中初始化检查下面的代码。 findViewById 成本很高,所以如果您找到尽可能少的 id 会更好

package com.example.thoma.event;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     Button thomasButton = (Button)findViewById(R.id.btn_Change);

     TextView thomasText = (TextView) findViewById(R.id.txt_View);

     thomasButton.setOnLongClickListener(new View.OnLongClickListener() {
        public boolean onLongClick(View v) {
            thomasText.setText("Artificial");

            // it will return false if long click wasnt long enough
            // and normal click will be called

            return true;
        }
    });

}

public void displayMessage(View v){
    TextView thomasText = (TextView)findViewById(R.id.txt_View);
    thomasText.setText(R.string.rsc_Text2);
}


}

关于java - android studio,无法识别按钮对象,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47974062/

相关文章:

java - 通过代码对齐 LinearLayout 中的 Imageview

java - 使用元素长度在对象数组中升序/降序

android - 如何使用 Strongloop Loopback REST API 包含和排序数组?

android - ubuntu14.04构建android4.4调制解调器报错

javascript - 如何在 JavaScript 中将对象返回到不同的作用域?

java - 在循环中创建多个对象问题

java - 下拉菜单打开 Bat 文件

java - 需要支持基于网络的身份验证

java - 在 libgdx 中绘制渐变的子集

android - Retrofit:处理动态更改名称的 JSON 对象