java - Android 按钮 Onclick

标签 java android

好的,我是 android dev 和 Java 的新手,所以我在点击方法时遇到了问题,这是我的代码。我知道我必须接近,提前谢谢。我想要我的按钮做的就是,当它在手机上单击以将布局 View 从 main.xml 切换到 xx.xml

package my.project;

import android.app.Activity;
import android.os.Bundle;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ExperiencerlActivity extends Activity {
    /** Called when the activ`enter code here`ity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);      
        Button button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
            }
        });
    }
}

这是我的按钮代码

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/linearLayout1"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="56dp"
    android:onClick="setLogin"
    android:text="Login" />

最佳答案

If you write like this in Button tag in xml file : android:onClick="setLogin" then

这样做:

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

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/btn"
    android:onClick="onClickBtn" />

</LinearLayout>

在代码部分:

public class StartUpActivity extends Activity 
{
    public void onCreate(Bundle savedInstanceState) 
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);    
    }

    public void onClickBtn(View v)
    {
        Toast.makeText(this, "Clicked on Button", Toast.LENGTH_LONG).show();
    } 
}

而且不需要这一切:

 Button button = (Button) findViewById(R.id.button1);
 button.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
 });

检查一次;

关于java - Android 按钮 Onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10231309/

相关文章:

java - 麦克风直播不清晰

Java 7 并行执行并未使用倒计时锁存器提高 REST API 的性能

Android 菜单项定义启用/禁用状态的样式

java - 建议在移动设备上使用对象池 : evil on desktop,。这怎么可能?

android - java.lang.VerifyError : Rejecting class 错误

java - 音频内存泄漏?

android - 唤醒 Google Glass 屏幕以根据位置显示当前信息

java - GAE 上静态图像最有效的方法?

java - 这种设计模式怎么称呼呢? ( map 而不是开关)

java - 为什么 Git Bash 没有使用 PATH 环境变量中定义的正确 Java 路径?