如何在Android平台上创建按钮

时间:2013-11-04 22:50:57

标签: java android android-studio

我在Android项目中创建了一个按钮,但它不起作用。 这是我的应用程序(基于'hello world'):

activity_main.xml中

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, I am a TextView" />

    <Button android:id="@+id/button_roy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, I am a Button" />

</LinearLayout>

这是我的java roy.java

package aa.aa.aaaaaaa.royb;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * Created by royb on 05/11/13.
 */
public class roy  extends Activity {
    public void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button createBtn = (Button) findViewById(R.id.button_roy);
        createBtn.setOnClickListener(new View.OnClickListener()
        {
            public void onClick (View v)
            {
                Context context = getApplicationContext();
                CharSequence text = "Hello toast!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
        });
    }
}

当我在我的Android设备上运行它并单击按钮时它没有做任何事情。 如何进行吐司显示?

1 个答案:

答案 0 :(得分:0)

public class Roy  extends Activity
{ 
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         Button createBtn = (Button) findViewById(R.id.button_roy);
        createBtn.setOnClickListener(new View.OnClickListener()
        {
            public void onClick (View v)
            {
                   Toast.makeText(getApplicationContext,"HelloToast",Toast.LENGTH_SHORT).show();
            }
        }
}