如何在Android Studio中通过连续按下按钮来增加Firebase的价值

9wbgstp7  于 2023-06-20  发布在  Android
关注(0)|答案(2)|浏览(112)

我刚开始使用Android Studio,现在我想创建一些按钮,每当我单击按钮时,这些按钮可以增加Firebase实时数据库的值。但是,我想让值在我长按按钮时保持增加,当我释放按钮时,值返回到零。下面是我的MainActivity代码:

package com.example.try6;

import androidx.appcompat.app.AppCompatActivity;

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.try6.databinding.ActivityMainBinding;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;
    private DatabaseReference database;
    private int number = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        initializeComponents();

    }

    private void initializeComponents() {
        Button[] buttons = {
                binding.btnGasUp, binding.btnGasDown,
                binding.btnYawRight, binding.btnYawLeft,
                binding.btnRollRight, binding.btnRollLeft,
                binding.btnPitchFront, binding.btnPitchBack,
        };
        for (Button button : buttons) {
            button.setOnClickListener(view -> {
                if (button == binding.btnGasUp) {
                    setOnClick(1, "Gas");
                } else if (button == binding.btnGasDown) {
                    setOnClick(-1, "Gas");
                } else if (button == binding.btnYawRight) {
                    setOnClick(1, "Yaw");
                } else if (button == binding.btnYawLeft) {
                    setOnClick(-1, "Yaw");
                } else if (button == binding.btnRollRight) {
                    setOnClick(1, "Roll");
                } else if (button == binding.btnRollLeft) {
                    setOnClick(-1, "Roll");
                } else if (button == binding.btnPitchFront) {
                    setOnClick(1, "Pitch");
                } else if (button == binding.btnPitchBack) {
                    setOnClick(-1, "Pitch");
                }
            });
            button.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    if (button == binding.btnGasUp) {
                        setOnLongClick(number++, "Gas");
                    } else if (button == binding.btnGasDown) {
                        setOnLongClick(number--,"Gas");
                    } else if (button == binding.btnYawRight) {
                        setOnLongClick(number++,"Yaw");
                    } else if (button == binding.btnYawLeft) {
                        setOnLongClick(number--,"Yaw");
                    } else if (button == binding.btnRollRight) {
                        setOnLongClick(number++,"Roll");
                    } else if (button == binding.btnRollLeft) {
                        setOnLongClick(number--,"Roll");
                    } else if (button == binding.btnPitchFront) {
                        setOnLongClick(number++, "Pitch");
                    } else if (button == binding.btnPitchBack) {
                        setOnLongClick(number--,"Pitch");
                    }
                    number = 0;
                    return true;
                }
            });
        }
    }

    private void setOnClick(int increment, String path) {
        database = FirebaseDatabase.getInstance().getReference("Control");
        database.child(path).setValue(ServerValue.increment(increment)).addOnFailureListener(e -> {
            CharSequence text = "The value was failed to add";
            int toast = Toast.LENGTH_SHORT;
            Toast.makeText(getApplicationContext(), text, toast).show();
        });
    }
    private void setOnLongClick(int increment, String path){
        database = FirebaseDatabase.getInstance().getReference("Control");
        database.child(path).setValue(ServerValue.increment(increment)).addOnFailureListener(e -> {
            CharSequence text = "The value was failed to add";
            int toast = Toast.LENGTH_SHORT;
            Toast.makeText(getApplicationContext(), text, toast).show();
        });
    }

}

这就是结果:The Result on Firebase Realtime Database
它适用于setOnClickListener()事件,即使值没有返回到零(只要我单击按钮,值就会增加),但setOnLongClickListener()事件根本不起作用。有什么建议我该怎么做?还是我做错了什么?对不起,我的英语很差。

ukdjmx9f

ukdjmx9f1#

设计您的布局:
打开布局XML文件(例如activity_main.xml)并添加一个button元素。您可以根据需要自定义其外观。按钮的XML示例:

<Button
    android:id="@+id/increaseButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Increase"
    />

检索对Firebase实时数据库的引用:
在Activity或片段中,为Firebase Realtime Database引用声明一个变量。示例代码:

private DatabaseReference mDatabase;

初始化Firebase实时数据库引用:
在Activity的onCreate()方法或片段的onViewCreated()方法中,初始化数据库引用。示例代码:

mDatabase = FirebaseDatabase.getInstance().getReference();

为按钮设置单击和长单击监听器:
在您的Activity或片段中,通过按钮的ID找到按钮,并在其上设置单击侦听器和长单击侦听器。示例代码:

Button increaseButton = findViewById(R.id.increaseButton);

increaseButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        increaseValue();
    }
});

increaseButton.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        startIncreasingValue();
        return true;
    }
});

实现增加值的方法:
在Activity或片段中创建两个方法increaseValue()和startIncreasingValue(),以处理在Firebase中增加值和更新值的逻辑。示例代码:

private int value = 0;
private Handler handler = new Handler();
private Runnable increaseRunnable;

private void increaseValue() {
    value++;
    mDatabase.child("your_node_path").setValue(value);
}

private void startIncreasingValue() {
    increaseRunnable = new Runnable() {
        @Override
        public void run() {
            increaseValue();
            handler.postDelayed(this, 100); // Increase every 100 milliseconds
        }
    };
    handler.post(increaseRunnable);
}

释放按钮时停止增加值:
覆盖Activity或片段中的onTouchEvent()方法,并在释放按钮时停止递增机制。示例代码:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_UP) {
        stopIncreasingValue();
    }
    return super.onTouchEvent(event);
}

private void stopIncreasingValue() {
    if (increaseRunnable != null) {
        handler.removeCallbacks(increaseRunnable);
        increaseRunnable = null;
    }
    value = 0;
    mDatabase.child("your_node_path").setValue(value);
}

请记住将“your_node_path”替换为Firebase实时数据库中所需节点的实际路径。
这些步骤将允许您在Android应用程序中创建一个按钮,该按钮在单击时增加Firebase Realtime Database中的值,并在长按时保持增加。释放按钮时,该值将重置为零。
请让我知道如果你有任何问题:)

mo49yndu

mo49yndu2#

假设你有一个包含按钮的布局,看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/longPressButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Long Press Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

要实现在按下按钮和释放按钮时每500毫秒递增一个值的功能,将值设置为零,请在Activity中定义五个全局变量:

private Button longPressButton;
private Handler toastHandler;
private Runnable toastRunnable;
private boolean isButtonPressed;
private DatabaseReference valueRef;

onCreate()中,添加以下代码行:

longPressButton = findViewById(R.id.longPressButton);
toastHandler = new Handler();
isButtonPressed = false;
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
valueRef = db.child("value");

longPressButton.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isButtonPressed = true;
                incrementRepeatedly();
                return true;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                isButtonPressed = false;
                setValueToZero();
                return true;
        }
        return false;
    }
});

以下是相应的方法:

private void incrementRepeatedly() {
    toastRunnable = new Runnable() {
        @Override
        public void run() {
            if (isButtonPressed) {
                valueRef.setValue(ServerValue.increment(1));
                toastHandler.postDelayed(this, 500);
            }
        }
    };
    toastHandler.postDelayed(toastRunnable, 500);
}

private void setValueToZero() {
    valueRef.setValue(0);

}

要使其在项目中工作,必须在数据库中设置自己的引用。

相关问题