如何在 Java 中添加 sendMessage() 函数?

How to add sendMessage() function in Java?

我正在使用 https://developer.android.com/training/basics/firstapp/starting-activity 进行学习,但我对 sendMessage() 的编写不正确感到困惑,所以你能帮我解决这个问题吗?

这很简单,伙计,sendMessage() 方法应该由您在示例中看到的接收视图来编写,它将允许您直接在按钮中使用此方法。您必须使用 android:onClick="sendMessage()".

在 .xml 文件中的按钮 "send" 上调用此方法

它将是这样的:

public class MainActivity extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.editText);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent); 
}
}

xml 文件中的按钮如下所示:

<Button 
    android:id="@+id/btn_send"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Send"
    android:onClick="sendMessage()"/>

祝你好运!!!