textview 不显示长值

textview not showing long values

我正在实现一个定时器,下面是它的代码, 主要Activity

public class DepthActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_depth);
        findViewById(R.id.btn).setOnClickListener(this);
    }

    long startTime;
    boolean showingFirst = true;

    public void generate(View view) {
        if(showingFirst 
            startTime = System.currentTimeMillis();
            showingFirst = false;
        } else {
            long difference = System.currentTimeMillis() - startTime;
            TextView myText = findViewById(R.id.tv);
            myText.setText(String.valueOf(difference));
            showingFirst = true;
        }
    }

    @Override
    public void onClick(View v) {

    }
}

activity_main.xml

<Button
    android:id="@+id/btn"
    android:layout_width="339dp"
    android:layout_height="237dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="start/stop"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.83"
    android:onClick="generate"/>

<TextView
    android:id="@+id/tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="TextView"
    android:textSize="30sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

但是当我第二次单击该按钮时它不显示 "long dffrence" 并且 textview 保持空白。 它也没有在日志中显示任何错误 请帮助并感谢您的建议

在清单中,您将 Button 中的 clickListener 声明为 generate()

但是在 Activity 的 onCreate,你覆盖了它 findViewById(R.id.btn).setOnClickListener(this);

onCreate 中删除 findViewById(R.id.btn).setOnClickListener(this); 或在 onClick 中调用 generate(v)

你应该删除

 findViewById(R.id.btn).setOnClickListener(this);

来自 onCreate()

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_depth);
    }

这样 onClick 将按布局 xml 文件处理。