如何从设置 Activity 修改 MainActivity 上的数据?

How do i modify data on my MainActivity from Settings Activity?

我已经尝试了很多其他话题和文章,但我就是找不到我要找的合适的东西。 所以我有一个 MainActivity 和一个 SettingsActivity 都是 java 类。在我的主要 activity 中有一个按钮,当按下时,计数增加 +1,并在 TextView 上显示它,它还会使设备在每次按下 increment/Every 按钮时振动。我想在 SettingsActivity 中设置一个 switchpreference,如果保持 off/false,则关闭按钮按下时的振动,如果保持 on/true,则打开按钮按下时的振动。 我不知道如何从 SettingsActivity 中检索 SwitchPreferenceCompat(ON OR OFF) 的状态并在 MainActivity 中使用它,所以如果用户在设置 activity 中关闭开关,振动应该停止在 MainActivity 中的按钮按下时。 我已经在 MainActivity 中使用共享首选项在应用程序关闭时保存当前 count/number 并在重新打开时从相同的计数恢复。

MainAcitivity

package com.saad.tapcounter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.preference.PreferenceManager;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends AppCompatActivity {

    private AdView mAdView ;
    int Start;
    TextView txt;
    Button btnU,btnT,btnR;
    Switch sw,sw2;
    private ConstraintLayout Clayout;
    Vibrator vibe;

    Boolean switchPref;

    SharedPreferences sharedPreferences;

    private static long back_pressed;
    private Vibrator Vibrator;

    //Double Tap Exit
    @Override
    public void onBackPressed()
    {
        if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
        else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
        back_pressed = System.currentTimeMillis();
    }


    //Inflater for Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu,menu);
        return true;

    }

    //Menu
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()){
            case R.id.menui1:
                startActivity(new Intent(this, SettingsActivity.class));

                return true;


            default:
                return super.onOptionsItemSelected(item);
        }
    }

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


        Toolbar toolbar = findViewById(R.id.toolbarid);
        setSupportActionBar(toolbar);


        MobileAds.initialize(this, "-APPID-");
        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);

        vibe =(Vibrator)getSystemService(VIBRATOR_SERVICE);
        Clayout = findViewById(R.id.MainLayout);
        btnT =  findViewById(R.id.tapbtn);
        btnR =  findViewById(R.id.resetbtn);
        btnU =  findViewById(R.id.undobtn);
        sw = findViewById(R.id.swch);
        sw2 = findViewById(R.id.darkswch);
        txt =  findViewById(R.id.txtv);
        txt.setTextColor(Color.BLACK);
        sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);

        loadData();
        setData();
        incrementbtn();
        undobtn();
        resetbtn();
        switchbtn();
        themeswitch();
        

    }
    public void loadData(){
        sharedPreferences = getSharedPreferences("0",MODE_PRIVATE);
    }

    private void setData(){
        Start = sharedPreferences.getInt("0",0);
        if(Start==0){
            txt.setText("0");
        }
        else{
            txt.setText(Integer.toString(Start));
        }
    }

    public void incrementbtn(){
        btnT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                incvibe();
                if (Start != 0) {
                    Start = sharedPreferences.getInt("0", 0);
                    Start += 1;
                    txt.setText(Integer.toString(Start));
                    txtresize();
                } else {
                    Start += 1;
                    txt.setText(Integer.toString(Start));
                }
                sharedPreferences.edit().putInt("0", Start).apply();
            }
        });
    }

    public void undobtn(){
        btnU.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                undovibe();
                if (Start != 0) {
                    Start = sharedPreferences.getInt("0", 0);
                    Start -= 1;
                    txt.setText(Integer.toString(Start));
                }
                else{
                    return;
                }
                sharedPreferences.edit().putInt("0", Start).apply();
            }
        });
    }

    public void resetbtn(){
        btnR.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetvibe();
                Start = 0;
                txt.setText(Integer.toString(Start));
                sharedPreferences.edit().putInt("0", Start).apply();

            }
        });
    }

    public void switchbtn(){
        sw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sw.isChecked()) {
                    btnR.setEnabled(false);
                    btnT.setEnabled(false);
                    btnU.setEnabled(false);
                    txt.setTextColor(Color.RED);
                }
                else{
                    btnR.setEnabled(true);
                    btnT.setEnabled(true);
                    btnU.setEnabled(true);
                    if(sw2.isChecked()){
                        txt.setTextColor(Color.WHITE);
                    }
                    else{
                        txt.setTextColor(Color.BLACK);
                    }
                }
            }
        });
    }

    public void themeswitch(){
        sw2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(sw2.isChecked()){
                    Clayout.setBackgroundColor(Color.DKGRAY);

                    if(sw.isChecked()){
                        txt.setTextColor(Color.RED);
                    }
                    else{
                        txt.setTextColor(Color.WHITE);
                    }
                }
                else{
                    Clayout.setBackgroundColor(Color.WHITE);
                    if(sw.isChecked()){
                        txt.setTextColor(Color.RED);
                    }
                    else{
                        txt.setTextColor(Color.BLACK);
                    }

                }
            }
        });

    }

    public void txtresize(){

        if(Start > 1000 && Start < 10000){
            txt.setTextSize(80);
        }
        else if (Start > 10000 && Start < 100000){
            txt.setTextSize(60);
        }
        else if (Start > 100000){
            txt.setTextSize(40);
        }
        else{
            return;
        }
    }
    StringBuilder info = new StringBuilder();


    public void undovibe(){
        vibe.vibrate(100);
    }

    public void resetvibe(){
        vibe.vibrate(150);
    }

    public void incvibe(){
        vibe.vibrate(40);
    }

}//Real one

SettingActivity(从 NEW > SettingActivity 创建) 我确实在这里自己尝试了一些东西,但它使我的应用程序崩溃了。

package com.saad.tapcounter;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;

public class SettingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    public static class SettingsFragment extends PreferenceFragmentCompat {
        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

        }
    }



}

root_preference.xml

<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory app:title="Settings"
        app:iconSpaceReserved="false">

        <SwitchPreferenceCompat
            app:key="Switchsett1"
            app:title="Vibration"
            app:summaryOff="Turn Vibration On"
            app:summaryOn="Turn Vibration Off"
            app:iconSpaceReserved="false"
            app:defaultValue="true"
            />

        <SwitchPreferenceCompat
            app:key="Switchset2"
            app:iconSpaceReserved="false"
            app:summaryOff="@string/attachment_summary_off"
            app:summaryOn="@string/attachment_summary_on"
            app:title="@string/attachment_title" />

    </PreferenceCategory>

</PreferenceScreen>

I don't know how to retrieve the state of switch(ON OR OFF) from SettingsActivity

要从共享首选项中获取 SwitchPreferenceCompat 的值,您需要将其检索为 Boolean

现在你的第一个 SwitchPreferenceCompat 的键是 Switchsett1,所以要检索这个值:

public class MainActivity extends AppCompatActivity {

    Boolean switchPref;

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

        ....

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        switchPref = prefs.getBoolean("Switchsett1", false);
        Toast.makeText(this, String.valueOf(switchPref), Toast.LENGTH_SHORT).show(); // shows true if the SwitchPreferenceCompat is ON, and false if OFF.

现在,如果 SwitchPreferenceCompat 打开,上面脚本中的 Toast 显示 true,如果关闭,则显示 false

您可以为 Switchset2 SwitchPreferenceCompat

做同样的事情