如何从secondActivity获取切换按钮的值?

时间:2017-09-10 20:24:05

标签: java android

在我的项目中我有2个活动,在第二个活动中我有一个切换按钮。

我有两个问题:

1:我想从第二个活动中获取切换按钮的值并通过使用共享首选项将其传递给第一个活动,以便在第一个活动中显示吐司,但是我没有获得切换按钮的值,因此吐司无法正常工作

2:当我按下或关闭应用程序时,开关按钮的值变为默认值,如何保存开关按钮的值?

这是我的第一个活动:

 public class MainActivity extends AppCompatActivity {


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

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    Boolean isChecked = settings.getBoolean("status" , false);

    if (isChecked){
        Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
    }


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_setting:
            Intent settingIntent = new Intent(getApplicationContext(), Main2Activity.class);
            startActivity(settingIntent);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

}

这是我的第二项活动:

 public class Main2Activity extends AppCompatActivity {

Switch aSwitch;
EditText editText;
Button back;

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

    editText = (EditText) findViewById(R.id.editText);
    aSwitch = (Switch) findViewById(R.id.switch1);



    back = (Button) findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(swIntent);
        }
    });

}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean("MySwitch", true);
    super.onSaveInstanceState(outState);
}

public void enable_disable(View view) {
    if (aSwitch.isChecked()) {

        SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
        editor.putBoolean("status", true);
        editor.commit();
    } else {
        SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
        editor.putBoolean("status", false);
        editor.commit();
    }
}

}

这是我第二次活动的布局:

 <LinearLayout 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"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">



<Switch
    android:id="@+id/switch1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="enable_disable"
    android:text="Switch" />

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/btnBack"
    android:text="Back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

2 个答案:

答案 0 :(得分:0)

SharedPreferences只是存储在设备上的键值xml文件。您遇到的问题是您使用两个不同的SharedPreferences,这就是为什么值没有出现的原因。

在您使用该行的SecondActivity中:

getSharedPreferences("switch", MODE_PRIVATE).edit();

您正在创建一个名为switch.xml的SharedPreferences文件,并将开关的值存储在其中。但是,当您致电MainActivity时:

PreferenceManager.getDefaultSharedPreferences(this);

这将获取“默认文件”,这是一个不同的xml文件,因此该值不存在。您需要与两个活动之间访问的SharedPreferences文件保持一致。在这种情况下,我建议您只使用默认文件并将SecondActivity更改为:

SharedPreferences.Editor editor = PreferenceManager
    .getDefaultSharedPreferences(this)
    .edit();

editor.putBoolean("status", true);
editor.commit();

现在,该值将保存在默认文件中,该文件与您在MainActivity

中的读数相同

答案 1 :(得分:0)

使用switch onChangedListener。这将在您的Main2Activity中保留您的开关状态

public class Main2Activity extends AppCompatActivity {

Switch aSwitch;
Button back;

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

    aSwitch = (Switch) findViewById(R.id.switch1);
    SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
    boolean isChecked = sharedPreference.getBoolean("status",false);
    Log.d("Shriyansh",isChecked+"");
    aSwitch.setChecked(isChecked);
    aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // do something, the isChecked will be
            // true if the switch is in the On position
            SharedPreferences.Editor editor = getSharedPreferences("switch", MODE_PRIVATE).edit();
            editor.putBoolean("status", isChecked);
            editor.commit();
            Log.d("Shriyansh1",isChecked+"");
        }
    });

    back = (Button) findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent swIntent = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(swIntent);
        }
    });

}

现在要在第一个活动中显示吐司,您可以在MainActivity的onResume()方法中使用此首选项

public class MainActivity extends AppCompatActivity {

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

@Override
protected void onResume() {
    super.onResume();
    SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);
    boolean isChecked = sharedPreference.getBoolean("status",false);
    if (isChecked){
        Toast.makeText(this, "Enabled", Toast.LENGTH_SHORT).show();
    }else {
        Toast.makeText(this, "Disabled", Toast.LENGTH_SHORT).show();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
    case R.id.action_setting:
        Intent settingIntent = new Intent(getApplicationContext(), 
               Main2Activity.class);
        startActivity(settingIntent);
        return true;
    }
    return super.onOptionsItemSelected(item);
 }
}

Main2Activity的布局删除了开关的enable_disable方法

<LinearLayout 
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"
android:orientation="vertical"
android:layout_centerInParent="true"
android:gravity="center"
tools:context="a.switchtest.Main2Activity">



<Switch
    android:id="@+id/switch1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Switch" />

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<Button
    android:id="@+id/btnBack"
    android:text="Back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

您需要更换的MainActivity

PreferenceManager.getDefaultSharedPreferences(this);

SharedPreferences sharedPreference = getSharedPreferences("switch", MODE_PRIVATE);

也会从您的Main2Activity中删除它

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putBoolean("MySwitch", true);
    super.onSaveInstanceState(outState);
}