2

我正在尝试制作类似于游戏中的世界创造者,并且我正在使用共享首选项来存储数组等。但有一个问题。我正在尝试从另一个类更新它,所以我使用静态变量来这样做。但是当我用列表视图回到原来的类时,我发现没有任何更新。有任何想法吗?这是代码。哦,logcat中没有错误。

列表视图类。

package you.don't.need-to-know;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class WorldMenu extends  ListActivity{
public static SharedPreferences prefs = null;
static String splitter;
String[] worldList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    splitter =  "Create World," + prefs.getString("worldString", "");
    worldList = splitter.split(",");
    setListAdapter(new ArrayAdapter<String>(WorldMenu.this,
    android.R.layout.simple_list_item_1, worldList));


}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    if(position == 0){
        Intent openWorldNamer = new                                           
 Intent("you.don't.need-to-know");
        startActivity(openWorldNamer);
    }

}


}

更新者:

package you.don't.need-to-know;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
static String updater;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_worldcreator);
    worldNameEditor = (EditText) findViewById(R.id.editText1);
    saver = (Button) findViewById(R.id.button1);
    updater = worldNameEditor.getText().toString() + ",";
    saver.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Editor editor = WorldMenu.prefs.edit();
            editor.putString("worldString", updater);
            editor.commit();
            Intent openListWorld = new
 Intent("you.don't.need.to-know");
            startActivity(openListWorld);
        }
    });
}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();

}

}

编辑:新代码更新更接近修复。更新程序和列表活动

更新者:

 import android.app.Activity;

 import android.content.Intent;

 import android.content.SharedPreferences;

 import android.content.SharedPreferences.Editor;

 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;

 import android.os.Bundle;

 import android.preference.PreferenceManager;

 import android.view.View;

 import android.widget.Button;

 import android.widget.EditText;


public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_worldcreator);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    worldNameEditor = (EditText) findViewById(R.id.hello);
    saver = (Button) findViewById(R.id.button1);
    updater = worldNameEditor.getText().toString() + ",";

saver.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        listener = new SharedPreferences.OnSharedPreferenceChangeListener()  
{
            public void onSharedPreferenceChanged(SharedPreferences      
  prefs, String key) {
                editor = prefs.edit();
                editor.putString("worldString", updater);   
                editor.commit();
              }
            };

            prefs.registerOnSharedPreferenceChangeListener(listener);
            Intent openListWorld = new                                    
 Intent("");
            startActivity(openListWorld);

    }});

    }
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();





    }





@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

}
}

列出活动:

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class WorldMenu extends  ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    splitter =  "Create World," + prefs.getString("worldString", "hello");
    worldList = splitter.split(",");
    setListAdapter(new ArrayAdapter<String>(WorldMenu.this,          
 android.R.layout.simple_list_item_1, worldList));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    if(position == 0){
        Intent openWorldNamer = new                                          
Intent("");
        startActivity(openWorldNamer);
    }

}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
}


}
4

4 回答 4

2

您似乎没有在监视共享首选项的变化。看:

http://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener.html

final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    // update your listview.
  }
};

prefs.registerOnSharedPreferenceChangeListener(listener);

因此,当您收到该回调时,它会告诉您更改了哪个键。然后,您可以更新列表视图的适配器以获取新内容并在适配器中调用 onDataSetChanged()。

或者,您可以将适配器设置代码移动到 onResume() 函数中。这样当您的活动恢复时,您可以检查共享首选项的状态并设置适配器。但请注意,如果用户已将列表向下滚动了一段距离,并且您在简历中再次调用 setAdapter(),他们将失去滚动位置。

编辑:

尝试:

更新程序(这不应该需要开始一个新的活动,这可以完成()):

import android.app.Activity;

 import android.content.Intent;

 import android.content.SharedPreferences;

 import android.content.SharedPreferences.Editor;

 import android.content.SharedPreferences.OnSharedPreferenceChangeListener;

 import android.os.Bundle;

 import android.preference.PreferenceManager;

 import android.view.View;

 import android.widget.Button;

 import android.widget.EditText;


public class WorldCreator extends Activity{
EditText worldNameEditor;
Button saver;
SharedPreferences prefs;
OnSharedPreferenceChangeListener listener;
String updater;
Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_worldcreator);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    worldNameEditor = (EditText) findViewById(R.id.hello);
    saver = (Button) findViewById(R.id.button1);
    updater = worldNameEditor.getText().toString() + ",";

saver.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
           editor = prefs.edit();
           editor.putString("worldString", updater);   
           editor.commit();
           finish();
    }});

    }

列表显示:

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class WorldMenu extends  ListActivity{
SharedPreferences prefs = null;
String splitter;
String[] worldList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    // update your listview.
  }
};

prefs.registerOnSharedPreferenceChangeListener(listener);

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    splitter =  "Create World," + prefs.getString("worldString", "hello");
    worldList = splitter.split(",");
    setListAdapter(new ArrayAdapter<String>(WorldMenu.this,          
 android.R.layout.simple_list_item_1, worldList));
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    // TODO Auto-generated method stub
    super.onListItemClick(l, v, position, id);
    if(position == 0){
        Intent openWorldNamer = new                                          
Intent("");
        startActivity(openWorldNamer);
    }

}
}
于 2013-08-09T00:33:41.643 回答
2

偏好是在活动级别定义的。我会得到我的赏金。

调用 getActivity() 以获取调用者活动,然后使用它来获取偏好。如果你想要结构通过接口发回结果。实现接口并使用接口查找活动。Eclipse 为您创建存根。

这是一个完整的类,它只是更改了一个优先保存它并立即将结果发送回调用类。它使用 getActivity() 所以这两个类共享相同的优先级。它通过接口回调。

它来自我的应用程序 com.gosylvester.bestrides

    package com.gosylvester.bestrides;

import com.google.android.gms.maps.GoogleMap;

import android.support.v4.app.DialogFragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;

//...

public class MapSettings extends DialogFragment implements

    OnCheckedChangeListener {

public static final String MAP_TYPE = "com.gosylvester.bestrides.settings.maptype";
private int _mapType = -1;
BestRidesSettingsDialogListener activity;
SharedPreferences sharedpref;

public interface BestRidesSettingsDialogListener {
    void onMapSettingsChange(int mapType);
}

public MapSettings() {
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // the activity may be null if this is called without implementing the
    // BestRidesSettingsDialogListener (The settings object saves the
    // setting so the
    // call back may not be needed.

    activity = (BestRidesSettingsDialogListener) getActivity();

    getDialog().setTitle(R.string.app_name);
    View view = inflater.inflate(R.layout.activity_map_settings, container);
    RadioGroup rg = (RadioGroup) view.findViewById(R.id.radioGroup1);
    // initialize to the shared preferences value
    rg.clearCheck();
    sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
    int x = sharedpref.getInt(MAP_TYPE, GoogleMap.MAP_TYPE_NORMAL);
    RadioButton rb = null;

    switch (x) {
    case GoogleMap.MAP_TYPE_HYBRID:
        rb = (RadioButton) view.findViewById(R.id.RDOHybrid);
        rb.setChecked(true);
        break;
    case GoogleMap.MAP_TYPE_NORMAL:
        rb = (RadioButton) view.findViewById(R.id.RDORoad);
        rb.setChecked(true);
        break;
    case GoogleMap.MAP_TYPE_SATELLITE:
        rb = (RadioButton) view.findViewById(R.id.RDOSatelite);
        rb.setChecked(true);
        break;
    case GoogleMap.MAP_TYPE_TERRAIN:
        rb = (RadioButton) view.findViewById(R.id.RDOTerrain);
        rb.setChecked(true);
        break;
    }
    // set the listener after setting up
    rg.setOnCheckedChangeListener(this);
    return view;
}

public int getMapType() {
    return _mapType;
}

public void setMapType(int mapType) {
    this._mapType = mapType;
}

@Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
    // TODO Auto-generated method stub
    int mapType = 0;
    switch (checkId) {
    case R.id.RDORoad:
        mapType = GoogleMap.MAP_TYPE_NORMAL;
        break;
    case R.id.RDOHybrid:
        mapType = GoogleMap.MAP_TYPE_HYBRID;
        break;
    case R.id.RDOSatelite:
        mapType = GoogleMap.MAP_TYPE_SATELLITE;
        break;
    case R.id.RDOTerrain:
        mapType = GoogleMap.MAP_TYPE_TERRAIN;
        break;
    }
    // run the activity onchange
    // if the activity is null there is no listener to take action on the
    // settings
    if (activity != null) {
        activity.onMapSettingsChange(mapType);
    }

    // save the settings
    if (sharedpref == null) {
        sharedpref = getActivity().getPreferences(Context.MODE_PRIVATE);
    }
    sharedpref.edit().putInt(MAP_TYPE, mapType).commit();
}

}

/* 这是另一个类的片段 */

public class KmlReader extends FragmentActivity implements
        BestRidesSettingsDialogListener {

...

mMap.setMapType(sharedPref.getInt(
                com.gosylvester.bestrides.MapSettings.MAP_TYPE,
                GoogleMap.MAP_TYPE_NORMAL));

...

@Override
public void onMapSettingsChange(int mapType) {
    // TODO Auto-generated method stub
    if (mMap != null) {
        mMap.setMapType(mapType);
    }
}

祝你好运

于 2013-08-14T04:53:12.603 回答
1

如果所有类都在同一个进程中,则共享首选项意味着在多个类中使用。您不必显式地使用静态。只需在两个类中使用相同的 sharedpreference。

于 2013-08-09T00:34:45.997 回答
0

当您返回原始类时,它不能保证原始类的 onCreate 方法可以执行,就像其他答案所说,您可以将代码放入 onResume 方法,或者在 startActivity(intent) 添加方法 finish() 以完成当前活动

于 2013-08-09T02:48:02.643 回答