簡體   English   中英

未調用OnClick方法

[英]OnClick Method is not being called

這是我的代碼:

public class MainActivity extends Activity implements View.OnClickListener {

    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b = (Button) findViewById(R.id.button1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.button1:
                Toast.makeText(getApplicationContext(), "onClick method was called", Toast.LENGTH_LONG).show();
                break;
            }
        }
    }

由於某種原因,什么也沒發生,也沒有吐司。 我想念什么嗎? 謝謝

寫:

b.setOnClickListener(this);

onCreate

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(this);
    }

您必須將監聽器設置為按鈕,才能使onClick起作用

作為Vipul答案的替代方法,您還可以在XML布局文件的Button標記中添加onClick屬性。 例:

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="myMethod" />

</RelativeLayout>

並且,在您的MainActivity.java中,刪除View.OnClickListener實現的接口(感謝@donfuxx),添加以下方法:

public void myMethod(View v) {
    //do something
}

暫無
暫無

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

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