这是我的代码基本活动
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton compass1 = (FloatingActionButton)findViewById(R.id.comp);
compass1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(findViewById(R.id.relativeLayout1).getVisibility()==View.VISIBLE){
findViewById(R.id.relativeLayout1).setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),"Compass Has Been Disabled",Toast.LENGTH_SHORT).show();
}
else{
findViewById(R.id.relativeLayout1).setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Compass Has Been Enabled",Toast.LENGTH_SHORT).show();
}
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@覆盖 public boolean onNavigationItemSelected(MenuItem item){
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_first) {
Intent myIntent = new Intent(this,MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
finish();
} else if (id == R.id.nav_second) {
Intent myIntent = new Intent(this,SecondFloor.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
finish();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
答案 0 :(得分:1)
你不需要SharedPreferences
。只需传递具有指南针可见性状态的Intent extra。
从类别字段isCompassVisible
为SecondFloor
创建意图时:
Intent myIntent = new Intent(this,SecondFloor.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myIntent.putExtra("isCompassVisible", isCompassVisible);
startActivity(myIntent);
在SecondFloor
活动onCreate
(或您需要的任何地方):
if(getIntent().hasExtra("isComapssVisible")
comapssView.setVisibility(getIntent().getBooleanExtra("isCompassVisible", true) ? View.VISIBLE : View.GONE);
答案 1 :(得分:0)
1.您可以使用“共享”偏好设置将值设置为:
SharedPreferences sharedPreferences = getSharedPreferences(Values.SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isShowing", true/false);
editor.apply();
并将其作为:
SharedPreferences prefs = ((Activity)context).getSharedPreferences("TAG", Context.MODE_PRIVATE);
Boolean shown = prefs.getBoolean("isShowing",true);
只需将其传递给:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putBoolean("isShowing",true/false);
intent.putExtras(bundle);
startActivity(intent);
得到它:
Boolean b = getIntent().getBooleanExtra("isShowing",false);