导入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/