编辑ListView项并保存更改

时间:2014-06-16 14:11:29

标签: java android arrays listview android-listview

首先,我是Android的绝对初学者。我正在尝试创建一个ListView,它显示一个字符串数组中的项目,并允许用户只需单击要修改的项目即可编辑这些项目。这些更改也必须保存在字符串数组中。 这是我的代码(重要部分)和类:

MainActivity.java(通过Intent发送静态保存的数组(preSetDevices))

String preSetDevices [] = {"D4:92:9D:F5:1C:1A","E5:05:65:5E:C4:E7","ED:3E:77:06:9E:46"};

...
        btsetDevices = (Button) findViewById(R.id.setDevices);
        btsetDevices.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent myIntent = new Intent(MainActivity.this, SetDevices.class);
                myIntent.putExtra("array_set_devices", preSetDevices);
                startActivity(myIntent);

            }
        });

SetDevices.Java(接收意图,在ListView中显示该项目(这里是我想要修改项目并将这些更改保存在字符串数组中)

public class SetDevices extends Activity{

ListView lvResult;
Intent intent;
String[] array_devices_received;
ArrayAdapter<String> adapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.set_devices);
    registerClickCallBack();

     intent = getIntent();
     array_devices_received = intent.getStringArrayExtra("array_set_devices");

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

         adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array_devices_received);         
        lvResult.setAdapter(adapter); }

        private void registerClickCallBack() {
            lvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View viewClicked,int position, long id) {

//What do I have to put here to edit items of the listview and save changes in this array of string, (I will return this array modified to  MainActivity.java through Intent again later)

                }
            });

}

}

1 个答案:

答案 0 :(得分:0)

我认为使用ArrayList而不是简单数组会更容易和有效。

SetDevices类中,使用此示例代码方法将简单数组导入ArrayList:

public ArrayList<String> arrayToArrayList(String[] array){
    ArrayList<String> arrayList = new ArrayList<String>(array.length);
    for(String string : array){
        arrayList.add(string);
    }

    return arrayList;
}

然后在适配器中设置ArrayList并使用它的方法更新/编辑/删除ListView中的项目。

祝你好运!