当我按下指定按钮时,我设置的onClick事件没有触发

时间:2015-12-03 15:18:54

标签: android

我一直在为我所属的项目开发Android应用程序,而且我一直遇到一个问题我已经搜索了几天了。我一直遇到的问题是,出于某种原因,onClick事件没有触发我设置的按钮。

这是Java:

    public class Dashboard extends AppCompatActivity implements OnClickListener
{
    private Toast toast;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        final Button fuelPageButton;
        super.onCreate(savedInstanceState);
        fuelPageButton = (Button)findViewById(R.id.fuelButton);
        setContentView(R.layout.activity_main2);

        fuelPageButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v)
    {
        toast.makeText(Dashboard.this ,"Button pressed!", Toast.LENGTH_SHORT);
        //setContentView(R.layout.fuel_saved);
    }
}

以下是按钮的XML:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/fuelButton"
        android:layout_below="@+id/textView6"
        android:layout_alignBottom="@+id/textView7"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="48dp"
        android:layout_marginTop="-4dp"
        android:layout_marginRight="-1dp"
        android:layout_marginLeft="-2dp"
        android:clickable="true" />

2 个答案:

答案 0 :(得分:3)

您必须在致电setContentView之前致电findViewById

  @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        final Button fuelPageButton;
        fuelPageButton = (Button)findViewById(R.id.fuelButton);  
        fuelPageButton.setOnClickListener(this);
    }

答案 1 :(得分:1)

你举杯祝酒,但你并没有把.show()放在身后。它不会显示出来。

  toast.makeText(Dashboard.this ,"Button pressed!", Toast.LENGTH_SHORT).show();

在findviewbyid之前确实是setcontentview ...(参见@Arthur Korchagin)