[英]Error:(56, 21) error: non-static method getId() cannot be referenced from a static context
I am writing this code and it shows the error non-static method getID()
cannot be referenced from a static context.我正在编写这段代码,它显示错误非静态方法getID()
无法从 static 上下文中引用。 The error is in switch (View.getID())
错误在开关(View.getID())
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button greetbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
greetbutton = (Button) findViewById(R.id.greetbutton);
greetbutton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
TextView textView = (TextView) findViewById(R.id.textView);
EditText editFreindname = (EditText) findViewById(R.id.editFriendname);
String freindname = editFreindname.getText().toString();
switch (View.getId()) {
case R.id.greetbutton:
textView.setText(getString(R.string.greetstring) + freindname + "!");
break;
default:
break;
}
}
}
You need to replace View
with v
in your switch statement. 您需要在switch语句中将View
替换为v
。 View
is the name of the class, v
is the variable you are trying to compare. View
是类的名称, v
是您要比较的变量。
Please replace View with v. 请用v替换View。
try this v.getId() instead of View.getId() :) 试试这个v.getId()而不是View.getId():)
getId()
is not a static method. getId()
不是静态方法。 You need to call it on an instance of the View
class. 您需要在View
类的实例上调用它。
For example, these 3 uses of getId()
are valid ( EditText
extends TextView
, which extends View
): 例如, getId()
这三种用法是有效的( EditText
扩展了TextView
,扩展了View
):
editFreindname.getId()
freindname.getId()
v.getId()
You're calling the method as if it's static, since you're calling it using the class name: 您正在调用该方法,就好像它是静态的一样,因为您使用的是类名:
View.getId();
getId()
is non-static method you cannot call from a View
. getId()
是您不能从View
调用的非静态方法。
Try 尝试
switch (v.getId()) {
instead of 代替
switch (View.getId()) {
I hope it helps! 希望对您有所帮助!
You can't call the method using the class name.您不能使用 class 名称调用该方法。 You should use v instead of View.您应该使用 v 而不是 View。 ie IE
switch (v.getId()) {
case R.id.greetbutton:
textView.setText(getString(R.string.greetstring) + freindname + "!");
break;
default:
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.