0

使用以下代码,我收到 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 错误。

4

1 回答 1

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");

    }
}
于 2013-09-17T13:48:24.993 回答