0

我正在尝试在 android 开发中获取列表视图的位置。我想获取位置值并将其保存到 pref 文件中。我的代码是

public class Browse extends Activity {

private ListView mainListView;  
private ArrayAdapter<Card> listAdapter; 
public static final String userPrefs = "UserPrefs";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout2);

    mainListView = (ListView) findViewById( R.id.mainListView);  

    DatabaseHandler dh = new DatabaseHandler(this);

    // Remember to drop existing table if it exists
    dh.removeAll();

    // Insert 4 Lecturers into the database
    Log.d("Database: ", "Inserting values..");
    dh.addCard(new Card(1, "Katniss Evergreen", "11", "33", "55", "44",     R.drawable.katniss));
    dh.addCard(new Card(2, "Peeta Melark", "49", "44", "11", "65", R.drawable.peeta));
    dh.addCard(new Card(3, "Gale Hawthrone", "87", "32", "98", "50", R.drawable.gale));
    dh.addCard(new Card(4, "Haymitch", "30", "32", "45", "31", R.drawable.haymitch));
    dh.addCard(new Card(5, "Effie Trinket", "65", "54", "21", "34", R.drawable.effie));
    dh.addCard(new Card(6, "President Snow", "23", "45", "67", "21", R.drawable.snow));

    List<Card> list = dh.getAll();  

    // Create ArrayAdapter using the list of lecturers
    listAdapter = new ArrayAdapter<Card>(this, R.layout.simplerow, list);

    // Set the ArrayAdapter as the ListView's adapter.  
    mainListView.setAdapter( listAdapter );  

    mainListView.setOnItemClickListener(new OnItemClickListener() {


    @Override
    public void onItemClick(AdapterView<?> parent, View v, int position,
            long id) {
        // TODO Auto-generated method stub
        String value = mainListView.getItemAtPosition(position).toString();
        SharedPreferences sp;
        sp = getSharedPreferences(userPrefs, Activity.MODE_PRIVATE); 
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("name", value);
        editor.commit();
    }
    }); 



}



}

这可行,但它保存了实际名称,所以如果我单击 Katniss Evergreen,它将保存名称“Katniss Evergreen”。我不想要这个我想要位置值,比如 Katniss 为 1,Peeta 为 2 等。有人知道我该怎么做吗?我整个周末都在为此工作,只是无法理解它:(我对此很陌生。

4

2 回答 2

1

如果要将位置保存为解析为字符串的数字,请使用:

    String pos = Integer.toString(position);
于 2012-12-01T18:48:28.120 回答
1

您想从列表中获取位置还是从 Card 对象中获取值?

如果来自列表而不是您将position参数传递给onClick.

否则,尝试获取Card对象并从中获取价值。

@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
        long id) {
    Card card  = (Card) mainListView.getItemAtPosition(position);
    int value = card.getId(); // Or other method

    SharedPreferences sp;
    sp = getSharedPreferences(userPrefs, Activity.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sp.edit();
    editor.putInt("name", value);
    editor.commit();
}
于 2012-12-01T18:54:30.993 回答