通过SharedPreference更新ImageView重新创建活动?

时间:2018-07-16 05:43:48

标签: java android xml

我制作了一个应用程序,用户可以通过ListPreference将imageview的图像更改为其他团队徽标。从ListPreference中选择它后,它的确会更改为正确的图像,但是当在设备上运行时,好像整个活动都被重新创建(即先关闭然后重新打开)。有没有一种方法可以避免这种情况,因此它可以平滑地过渡到具有更新图像的MainActivity,而无需重新创建它。

这里是我的代码:

MainActivity:

     @Override
public void onWindowFocusChanged(boolean hasFocus) {
    SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String team_chooser = getPrefs.getString("prefSetImage","1");

    if(team_chooser.equals("1")){
        awayTeam.setImageResource(R.drawable.team1logo);
    }else if(team_chooser.equals("2")){
        awayTeam.setImageResource(R.drawable.team2logo);
    }else if(team_chooser.equals("3")){
        awayTeam.setImageResource(R.drawable.team3logo);
    }
    super.onWindowFocusChanged(hasFocus);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.team_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.team_settings) {
        Intent settingsIntent = new Intent(this, SettingsActivity.class);
        startActivity(settingsIntent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

SettingsActivity:

        @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    ActionBar actionBar = this.getSupportActionBar();

    if(actionBar != null){
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    int id = item.getItemId();
    if(id == android.R.id.home){
        NavUtils.navigateUpFromSameTask(this);
    }
    return super.onOptionsItemSelected(item);
}

清单:

    <activity
        android:name=".MainActivity"
        android:launchMode="singleTop">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SettingsActivity"
        android:label="@string/team"
        android:launchMode="singleTop"
        android:parentActivityName=".MainActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity"/>
    </activity>

1 个答案:

答案 0 :(得分:0)

是的,有时会造成问题,因此您只需将代码放在onResume()中即可。希望对您有所帮助。