創建列表視圖(ListView)的 OnItemClickListener(), 當用戶點擊列表視圖的一個項目, 然後打開一個對話框, 如果用戶點擊"OK", 此一項目將被刪除.
佈局文件(main.xml)無需修改, 參閱前文"動態添加列表視圖(ListView)的內容".
修改主要代碼 AndroidDynList.java, 添加 listViewOnItemClickListener.
package com.AndroidDynList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class AndroidDynList extends Activity {
EditText input;
Button add, clear;
ListView listview;
ArrayAdapter<String> MyArrayAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
input = (EditText)findViewById(R.id.input);
add = (Button)findViewById(R.id.add);
clear = (Button)findViewById(R.id.clear);
listview = (ListView)findViewById(R.id.list);
MyArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listview.setAdapter(MyArrayAdapter);
add.setOnClickListener(addOnClickListener);
clear.setOnClickListener(clearOnClickListener);
listview.setOnItemClickListener(listViewOnItemClickListener);
}
private Button.OnClickListener addOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String newInput = input.getText().toString();
MyArrayAdapter.add(newInput);
MyArrayAdapter.notifyDataSetChanged();
}};
private Button.OnClickListener clearOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
MyArrayAdapter.clear();
MyArrayAdapter.notifyDataSetChanged();
}};
private ListView.OnItemClickListener listViewOnItemClickListener
= new ListView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
final String strSelectedItem = parent.getItemAtPosition(position).toString();
AlertDialog.Builder delAlertDialog = new AlertDialog.Builder(AndroidDynList.this);
delAlertDialog.setTitle("- DELETE Selected Item? -");
delAlertDialog.setMessage(strSelectedItem);
delAlertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
MyArrayAdapter.remove(strSelectedItem);
MyArrayAdapter.notifyDataSetChanged();
}
});
delAlertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
//...
}
});
delAlertDialog.show();
}};
}
相關文章:
- 動態修改列表視圖(ListView)的內容
想問您 就是新增listview的內容要怎麼儲存
回覆刪除換頁面後內容還會留著 除非是自己刪除listview的內容
謝謝~