简体   繁体   中英

textview not showing long values

I am implementing a timer and following is the code for that, Main 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" />

But when i click the button second time it doesnt show "long dffrence" and textview remains blank. It is not also showing any error in log please help and thank you for your suggestions

At manifest you declare the clickListener from Button as generate() .

But at Activity's onCreate , you override it findViewById(R.id.btn).setOnClickListener(this); .

Remove findViewById(R.id.btn).setOnClickListener(this); from onCreate or call generate(v) inside onClick .

You should remove

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

from onCreate()

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

So that onClick will handle by layout xml file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM