错误:(56,21)错误:非静态方法getId()不能从静态上下文中引用
问题描述:
我正在编写此代码并显示错误非静态方法getID()
无法从静态上下文中引用。 该错误是在开关(View.getID())
错误:(56,21)错误:非静态方法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;
}
}
}
答
getId()
不是静态方法。您需要在View
类的实例上调用它。
例如,getId()
这3个用途是有效的(EditText
延伸TextView
,延伸View
):
editFreindname.getId()
freindname.getId()
v.getId()
答
您需要在switch语句来代替View
与v
。 View
是该类的名称,v
是您试图比较的变量。
答
你调用该方法,就好像它是静态的,因为你正在使用的类名调用它:
View.getId();
getId()
是你不能从一个View
调用非静态方法。
尝试
switch (v.getId()) {
,而不是
switch (View.getId()) {
我希望它能帮助!
答
请用v代替查看。
试试这个 v.getId()而不是View.getId():)