I have tried different things for quite some hours now, but I cannot seem to wrap my head around how to update a TextView when a user inputs a new text through an EditTextPreference in Android.
I use a switch statement in the onSharedPreferenceChanged method, inside an anonymous listener class. However, when i set player1View.setText(value), nothing happens. Is there an easier way of accomplishing this task – namely updating the textView through user input?
Here is the bit of code I cannot make work:
public class SettingsActivity extends AppCompatActivity
{
private TextView player1View;
private TextView player2View;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
@Override
protected void onCreate(Bundle savedInstanceState)
{
player1View = findViewById(R.id.player1);
player2View = findViewById(R.id.player2);
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
createListener();
}
private void createListener()
{
listener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
EditTextPreference etp = (EditTextPreference) sharedPreferences;
String value = sharedPreferences.getString("player_one", "NULL");
switch(key)
{
case "switch_setting1":
//Do something
break;
case "player1_key":
player1View.setText(value);
break;
case "player2_key":
player2View.setText(value);
break;
}
}
};
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.registerOnSharedPreferenceChangeListener(listener);
}
}
The screenshots below should emphasize more clearly what i mean. The fields I want to change are the ones named "Player 1" and "Player 2", and to accomplish that the user inputs new names through settings as shown.
Try maybe instead of:
String value = sharedPreferences.getString("player_one", "NULL");
This:
String value = sharedPreferences.getString("player_one", null);
or you might want to create two String variables(value, value2 for example), one for "player_one" and the other for "player_two" if you have forgot to add. I don't know exactly what you are trying to build.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.