在Toast中更改ListView的位置

时间:2012-11-01 03:12:45

标签: android listview position toast

这个代码当我点击第一项时,吐司显示我的位置0.我想当我点击第一项时,吐司显示我的位置1.

ListView myListView = (ListView) findViewById(R.id.myListView);
    final EditText myEditText = (EditText) findViewById(R.id.myEditText);

    final ArrayList<String> todoItem = new ArrayList<String>();
    final ArrayAdapter<String> aa;
    aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItem);
    myListView.setAdapter(aa);

    myEditText.setOnKeyListener(new OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(event.getAction() == KeyEvent.ACTION_DOWN)
                if((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) || keyCode == KeyEvent.KEYCODE_ENTER){
                    todoItem.add(0, myEditText.getText().toString());
                    aa.notifyDataSetChanged();
                    myEditText.setText("");
                    return true;
                }
            return false;
        }
    });

    myListView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                long arg3) {
            Toast.makeText(getApplicationContext(), "this is to do list " + position, Toast.LENGTH_SHORT).show();
        }
    });

2 个答案:

答案 0 :(得分:1)

As适配器中视图的位置从0开始,因此在Toast

中添加1到位置并显示
myListView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> arg0, View arg1, int position,
            long arg3) {
        Toast.makeText(getApplicationContext(), "this is to do list " + (position+1), Toast.LENGTH_SHORT).show();
    }
});

答案 1 :(得分:1)

只需将1添加到该位置,因为索引位置的值为0。

 public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
     Toast.makeText(getApplicationContext(), "this is to do list " + (position+1), Toast.LENGTH_SHORT).show();
 }