簡體   English   中英

如何在 Android 中實現啟動/停止“按鈕”

[英]How to implement a start/stop "button" in Android

我的目標是有一個CardView ,當點擊它時,它會從Start -> Stop開始,反之亦然。 在 CardView 內,我有兩個 TextView,我想在單擊它時對其進行更改。 這背后的功能是啟動前台服務並相應地停止它。

我對布局 xml 的想法:

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"> 

    <androidx.cardview.widget.CardView
        android:id="@+id/cardStartStop">

        <TextView
            android:id="@+id/txtCardStart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/card_start"
            app:drawableTopCompat="@drawable/ic_start_black_24dp" />

        <TextView
            android:id="@+id/txtCardStop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            android:text="@string/card_stop"
            app:drawableTopCompat="@drawable/ic_stop_circle_black_24dp" />
    </androidx.cardview.widget.CardView>

</GridLayout>

然后我想以編程方式更改每個 TextView 的可見性,並在關閉和重新打開應用程序時使用 SharedPreferences 保持其狀態。 我的問題更多是在設計層面,有沒有更好的方法來實現這一點,或者我指向正確的方向?

添加一個TextViewsetOnClickListener

XML 文件

<androidx.cardview.widget.CardView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
>
  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="Start"
    android:id="@+id/text_start_stop"
  />
  </androidx.cardview.widget.CardView>

班級

private TextView tStartStop;
Boolean flag = true;

點擊事件

tStartStop = findViewById(R.id.text_start_stop);
tStartStop.setOnClickListener(view -> {
  if (flag) {
    flag = false;
    tStartStop.setText("Start");
  } else {
    flag = true;
    tStartStop.setText("Stop");
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM