android开发中列表视图的位置

时间:2012-12-01 18:37:17

标签: android listview android-listview

我正试图在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”。我不想要这个我希望位置值如此为1代表Katniss,2代表Peeta等。任何人都知道如何做到这一点?我一直都在这个周末工作,只是无法理解它:(我对此很新。

2 个答案:

答案 0 :(得分:1)

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

    String pos = Integer.toString(position);

答案 1 :(得分: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();
}