Android编程中的java:如何调用接受View类型参数的方法?
好的,我试着按照这个教程:http://developer.安卓.com/training/index.html
我参加了ActionBar
培训。现在,我有了一个带有操作栏和按钮的应用程序。该按钮位于“编辑文本”字段旁边,如果您按下它,它只会将您带到另一个包含键入文本的视图
现在,我尝试调用相同的方法,使用操作栏菜单选项之一将您带到第二个视图。该处理程序位于主活动源代码中,我将其中的一个片段粘贴到此处:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
sendMessage();
return true;
case R.id.action_settings:
// openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void sendMessage(View view){
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
我想在switch操作中的一种情况下尝试调用sendMessage方法,但我不知道要放入哪些参数。单击按钮时,处理程序位于xml文件中:
<Button
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:text="@string/button_send"
安卓:onClick="sendMessage" />
我不知道这是怎么回事。我想做的事不可能吗?谢谢你的帮助
# 1 楼答案
# 2 楼答案
你不应该直接打电话
Android
当你按下Button
你在哪里声明android:onClick property
时调用它。如果您想在任何情况下调用它,只需传递一个null参数并检查null值# 3 楼答案
我认为可以通过将视图传递为null直接调用sendMessage()方法
# 4 楼答案
只需要做一个辅助函数
sendRealMessage
,然后在你的开关中调用这个函数另一种方法是通过空值
sendMessage(null)
调用函数,因为函数不直接使用它# 5 楼答案
可以在xml中用id命名按钮
android:id="+@id/buttonnamehere
然后从代码中调用按钮并执行单击操作使用方法:
Button mybut = (Button) findViewById(R.id.buttonnamehere);
点击:
mybut.performClick();