У меня есть 2 мероприятия. Один из них - основной вид деятельности. Одна из них - это предпочтение. Я пытаюсь изменить фоновый цвет действия на основе цвета, выбранного в RadioGroup в активности Preference.SharedPreference значения недоступны между действиями
Это файл класса для основного вида деятельности.
package com.example.mycsimodules;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ArrayAdapter;
public class ModList extends ActionBarActivity {
SharedPreferences savedData;
private String[] moduleArray = { "COMP 41600", "COMP 41620", "COMP 47330","COMP 30160", "COMP 30500", "COMP 40725", "COMP 41100", "COMP 41110" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mod_list);
savedData=getSharedPreferences("MyPrefs",0);
String colorMine=savedData.getString("color", "deflt");
TextView head=(TextView) findViewById(R.id.mymodlist);
head.setText(colorMine);
ArrayAdapter<String> moduleAdapter = new ArrayAdapter<String>(this, R.layout.activity_list_view, R.id.list1, moduleArray);
final ListView list = (ListView) findViewById(R.id.mod_list);
list.setAdapter(moduleAdapter);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mod_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent i=new Intent(this, Preferences.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
Это файл класса для класса Preference.
package com.example.mycsimodules;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class Preferences extends ActionBarActivity implements OnClickListener{
RadioGroup colorList;
Button saveButton;
SharedPreferences savedData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
colorList=(RadioGroup) findViewById(R.id.colorRadioGroup);
saveButton=(Button) findViewById(R.id.bSave);
saveButton.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.preferences, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressLint("NewApi") @Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==saveButton){
RadioButton myColor=(RadioButton) findViewById(colorList.getCheckedRadioButtonId());
String colorSelected=myColor.getText().toString();
TextView label=(TextView) findViewById(R.id.the_color_is);
label.setText(colorSelected);
savedData=getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor=savedData.edit();
editor.putString("color", colorSelected);
editor.apply();
editor.commit();
}
}
}
Я на самом деле не сделал цвет фона. Я просто пытаюсь показать значение в TextView в настоящее время. Но он показывает только значение по умолчанию все время. Я пытаюсь это сделать. Нажмите «Настройки». Нажмите на RadioButton для желаемого цвета. Нажмите кнопку «Сохранить». Нажмите на кнопку возврата, чтобы вернуться к основному действию.
Я довольно новичок в этом и, возможно, что-то делаю неправильно. Но я просто не могу понять, что это такое.
Ох. Огромное спасибо. Не могу поверить, что я весь день ломаю голову над этим. Это была такая глупость. Ты спасатель жизни. –
Без проблем друг. :) Это распространенная ошибка, не волнуйтесь. Если это решило вашу проблему, пожалуйста, отметьте ее как решение. Хорошего дня. –
И вот почему константы - хорошая идея. :) – kcoppock