我對編程知之甚少。我下載了Android Studio並開始修補它。我試圖製作應用程序,他們把它放在教程中,它的工作。不過,我試圖添加更多功能,迄今爲止失敗了。對不起,如果你看到我的代碼中有不必要的垃圾,我剛開始嘗試所有的東西,而且我感覺有點誤導。如何在Android Studio中保存開關的當前狀態?
反正,問題。我有一個帶有OnClick動作(change_font)的Switch(id:toggle_text)。當切換開關時,它應該通過intent1更改不同活動的字體大小。目前,它不僅不發送字體大小變量(該變量保持放置在getIntExtra上的默認值),但現在我試圖添加保存當前狀態的能力,它只顯示錯誤。這裏的代碼:
package com.example.myfirstapp;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ToggleButton;
import android.widget.TextView;
import static com.example.myfirstapp.R.id.toggle_text;
import static com.example.myfirstapp.R.string.change_font;
public class ShowAnOption extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_an_option);
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyz", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}
public void change_font(View v) {
int fssize;
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
fssize=20;
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
fssize=40;
}
Intent intent1 = new Intent (getBaseContext(), DisplayMessageActivity.class);
intent1.putExtra("Font_Size", fssize);
}
}
它說「無法解析符號toggle」toggle.setChecked()和if語句。我能做些什麼來解決這個問題?另外,爲什麼它不會被髮送到其他活動?以下是其他活動的代碼:
package com.example.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
Intent intent = getIntent();
Intent intent1 = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
int Font_Size = intent1.getIntExtra("Font_Size",50);
TextView textView = new TextView(this);
textView.setTextSize(Font_Size);
textView.setText(message);
ViewGroup layout = (ViewGroup) findViewById(R.id.activity_display_message);
layout.addView(textView);
}
}
感謝和抱歉,長時間閱讀。如果還有其他需要了解的信息,請告訴我,我很樂意展示。