簡體   English   中英

Button.setOnClickListener(this); 錯誤

[英]Button.setOnClickListener(this); error

這是代碼:

package com.elfapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button btn_Login;
    private EditText et_UserName;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        btn_Login = (Button)findViewById(R.id.button_login);
        btn_Login.setOnClickListener(this);

        et_UserName = (EditText)findViewById(R.id.editText_userName);

        setContentView(R.layout.main);
    }

    public void onClick(View v) {
        if (v.equals(btn_Login)) {
                // skriver ut en toast när man klickar på knappen
            //Toast.makeText(MainActivity.this, "Ansluter till server...", Toast.LENGTH_SHORT).show();

                // används i debuggern för att påvisa att programmet exekverat hit
            //Log.v("ThisApp", "onClick Successful");

                // TODO skickar det som står i et_UserName till controller (genom TCP/IP), som ska kolla om användaren finns
            Intent intent = new Intent(this, goListView);
            this.startActivity(intent);
        }
    }

}

當我到達btn_Login.setOnClickListener(this);時,程序崩潰btn_Login.setOnClickListener(this); 語句,我對執行該操作沒有太多的了解。(不習慣Eclipse調試器。)

試試看:將setContentView(R.layout.main)放在btn_Login = (Button)findViewById(R.id.button_login);

我想這會解決您的問題。 試一下

在初始化按鈕之前,移動setContentView(R.layout.main)調用。 這應該有所幫助。 祝好運!

我將使用其他示例,但是您可以改寫Java android類: android:onClick屬性可以定義一種單擊發生時將調用的方法。 這可能使用反射,並調用Class方法。

您的activity_main.xml上的按鈕定義:

<Button
    android:id="@+id/mapshow_button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtMsg"
    android:layout_alignLeft="@+id/editLog"
    android:layout_alignRight="@+id/txtLogitude"
    android:text="@string/lblBtnMap"
    android:textSize="10sp" 
    android:onClick="clickMap"/>

在活動類中創建一個方法:

public void clickMap(View v) {
    //TODO: do something    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM