我需要在按下另一个按钮时隐藏按钮

时间:2013-09-17 13:36:48

标签: android

使用以下代码我得到Null Pointer Exception错误。但是没有使用View我得到了正确的输出而没有隐藏按钮。(这只是禁用) 我的xml文件是:

 <Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/start_track"
    android:onClick="start"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
    android:id="@+id/button2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/stop_track"
    android:onClick="stop" 

    android:textAppearance="?android:attr/textAppearanceLarge"/>

我的活动代码是:

public void start(View v1)
{

    schedular = Executors.newSingleThreadScheduledExecutor();

    Toast.makeText(WelcomeActivity.this, "Tracking Started", Toast.LENGTH_SHORT).show();
    updateLocation();

    findViewById(R.id.button1).setEnabled(false);
    findViewById(R.id.button2).setEnabled(true);

    findViewById(R.id.button1).setVisibility(View.INVISIBLE);
    findViewById(R.id.button2).setVisibility(View.VISIBLE);


}

public void stop(View v2)
{

    Toast.makeText(WelcomeActivity.this, "Tracking Stopped", Toast.LENGTH_SHORT).show();
    schedular.shutdown();

    findViewById(R.id.button1).setEnabled(true);
    findViewById(R.id.button2).setEnabled(false);   

    findViewById(R.id.button1).setVisibility(View.VISIBLE);
    findViewById(R.id.button2).setVisibility(View.INVISIBLE);
}

请帮助我。我通过删除禁用代码行来尝试此代码。但我得到Null Pointer Exception错误。

1 个答案:

答案 0 :(得分:0)

您还可以尝试使用一个按钮并在点击时更改文字:

<Button
    android:id="@+id/button1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/start_track"
    android:onClick="doSth"
    android:textAppearance="?android:attr/textAppearanceLarge" />

private boolean clicked = false;

public void doSth(View v1)
{
    if(clicked) {

        Toast.makeText(WelcomeActivity.this, "Tracking Stopped", Toast.LENGTH_SHORT).show();
        schedular.shutdown();

        findViewById(R.id.button1).setText("Start tracking");

        clicked = false;
    } else {

        schedular = Executors.newSingleThreadScheduledExecutor();

        Toast.makeText(WelcomeActivity.this, "Tracking Started",  Toast.LENGTH_SHORT).show();
        updateLocation();

        findViewById(R.id.button1).setText("Stop tracking");

    }
}