[英]How to remove an item from ListView (Array list) in Android Studio?
I was building a simple app, where a user can add one liners to a list view and then on clicking that item in the list view, that item will be removed. 我正在构建一个简单的应用程序,用户可以在其中添加一个衬板到列表视图中,然后在列表视图中单击该项目时,该项目将被删除。
I have completed the adding part, however, I am facing a problem when it comes to removing the item by clicking on it. 我已经完成了添加部分,但是,在单击删除项目时遇到了问题。 My java code is as follows:
我的Java代码如下:
package com.example.supornochaudhury.schedulerapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.example.supornochaudhury.schedulerapplication.R.id.parent;
import static com.example.supornochaudhury.schedulerapplication.R.id.select_dialog_listview;
public class MainActivity extends AppCompatActivity {
ListView timesTableListView;
ArrayList<String> Works = new ArrayList<String>();
public void startWork (View view){
EditText edit = (EditText) findViewById(R.id.toDoEditText);
String name=edit.getText().toString();
Works.add(name);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_item, Works );
timesTableListView.setAdapter(arrayAdapter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timesTableListView = (ListView)findViewById(R.id.timesTableListView);
timesTableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG).show();
timesTableListView.removeViewAt(position);
}
});
}
}
After running this application on my phone, I am able to add without any issues, however, when I am clicking on any of the items, the app crashes. 在手机上运行该应用程序后,我可以添加而没有任何问题,但是,当我单击任何项目时,该应用程序将崩溃。
I would be indebted if anyone helps. 如果有人帮助我,我会很感激。 :)
:)
Use arrayAdapter as global. 使用arrayAdapter作为全局。 then remove an item from array list and use notifyDataSetChanged() to adapter
然后从数组列表中删除一个项目,并使用notifyDataSetChanged()适配器
timesTableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG).show();
Works.remov(position);
arrayAdapter.notifyDataSetChanged();
}
});
请首先删除从Works ArrayList中单击的项目,然后在适配器上调用notifyDataSetChanged()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.