如果单击,则从列表视图更改文本

时间:2013-07-29 09:57:21

标签: android sqlite android-listview textview

我需要帮助。 让我们说我有一个从数据库中获取的列表视图:

-- car

-- refrigerator

-- pencil

-- motorcycle

这就是我想要的。当我点击汽车或其他选项时,它将变为破碎。

-- broken

-- refrigerator

-- pencil

-- motorcycle

我之前用过

lv = (ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener()
{
 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
 {
     TextView mTextView = (TextView) arg1;
     mTextView.setText("broken");    
     //Toast.makeText(getApplicationContext(), data.get(arg2).toString(),3000).show();
 }});

问题是当我使用后退按钮并再次转到该页面时,它将像以前一样回来......

任何想法?????

这是我的完整代码

package com.test.first;

import java.util.ArrayList;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Listview extends Activity
{
SQLiteDatabase mydb;
ListView lv;
ArrayList data;
@Override
public void onCreate(Bundle savedInstanceState)
{ 
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);

//=====CODE FOR SHOWING THE DATA IN TOAST  =======
lv = (ListView) findViewById(R.id.listView);
lv.setOnItemClickListener(new OnItemClickListener()
{
 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
 {
     TextView mTextView = (TextView) arg1;
     mTextView.setText(data.get(arg2) + " has been bought !");


     //Toast.makeText(getApplicationContext(), data.get(arg2).toString(),3000).show();
 }});

mydb = Listview.this.openOrCreateDatabase("My", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS list (id INTEGER PRIMARY KEY AUTOINCREMENT,list varchar);");

data = new ArrayList();
//=VIEW BUTTON TO SHOW DATA INSERTED IN THE LISTVIEW=======       
Cursor cursor2=mydb.rawQuery("SELECT * FROM LIST;", null);

if (cursor2.moveToFirst())
{
    Toast.makeText(getApplicationContext(), "Shop List", 3000).show();
    data.clear();
    do
    {
        data.add(cursor2.getString(cursor2.getColumnIndex("list")));
    }
    while (cursor2.moveToNext());

//====CODE FOR SHOWING DATA AS A SIMPLE LIST ITEM=========================================
    ArrayAdapter <String> adapter=new ArrayAdapter<String>      (Listview.this,android.R.layout.simple_list_item_1,data);
    lv.setAdapter(adapter);

}
else
{
    Toast.makeText(getApplicationContext(), "DATA NOT AVAILABLE", 3000).show();
}
cursor2.close();
}
}

1 个答案:

答案 0 :(得分:0)

问题是当您按下后退按钮然后重新打开活动时,将使用原始信息重新创建ListView。此信息不会更改并包含Car文本,因此ListView在其他时间包含汽车文本是正常的 您应该更新列表信息,然后调用以修改ListView:

 adapter.notifyDataSetChanged()

如果您更改信息,然后按返回并重新打开Activty,ListView就可以了。