我无法弄清楚如何正确地将这段代码添加到我的MainActivity中

时间:2014-07-04 09:26:54

标签: java android eclipse

有人可以帮我添加:

/** Called when the user clicks the Send button. */
public void sendMessage(View view) {
    // Do something in response to button
}

到此(MainActivity):

package com.example.g;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main); 
    }
}

如何将这些结合起来并使其发挥作用?

3 个答案:

答案 0 :(得分:1)

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
}

/** Called when the user clicks the Send button */
public void sendMessage(View view) {`enter code here`
   // Do something in response to button
}
}

在activity_main.xml上使用如下内容:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="sendMessage"
    android:text="@string/button_send" />
</LinearLayout>

在strings.xml上添加以下行:

<string name="button_send">Send</string>

答案 1 :(得分:0)

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
    }

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    // Do something in response to button
}

}

答案 2 :(得分:0)

您需要在onCreate的完成位置添加它,如下所示:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
    }

    /** Called when the user clicks the Send button */
    public void sendMessage(View view) {
        // Do something in response to button 
    }
}

我假设xml中的按钮包含android:onClick="sendMessage"