有人能解释或建议一个教程,动态创建一个ListView在android?

以下是我的要求:

我应该能够通过按下按钮动态添加新元素。 应该足够简单易懂(例如,可能没有任何性能改进或convertView)

我知道关于这个话题有很多问题,但我找不到任何一个能回答我的问题。


当前回答

而不是

listItems.add("New Item");
adapter.notifyDataSetChanged();

您可以直接拨打

adapter.add("New Item");

其他回答

首先在项目的res/layout/main.xml文件夹中创建一个XML布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

这是一个简单的布局,顶部有一个按钮,底部有一个列表视图。注意,ListView有id @android:id/list,它定义了ListActivity可以使用的默认ListView。

public class ListViewDemo extends ListActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        adapter=new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }
}

android.R.layout。simple_list_item_1是Android提供的默认列表项布局,你可以使用这个库存布局来处理不复杂的事情。

listItems是一个列表,它包含ListView中显示的数据。所有的插入和删除都应该在listItems上完成;listItems中的变化应该反映在视图中。这是由ArrayAdapter<String>适配器处理的,它应该被通知使用:

adapter.notifyDataSetChanged ();

一个Adapter是用3个参数实例化的:context,它可以是activity/listactivity;个人列表项的布局;最后是列表,它是列表中显示的实际数据。

        This is the simple answer how to add datas dynamically in listview android kotlin


class MainActivity : AppCompatActivity(){
        
            var listItems = arrayListOf<String>()
            val array = arrayOf("a","b","c","d","e")
            var listView: ListView? = null
    
            private lateinit var adapter: listViewAdapter
        
            override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.scrollview_layout)
        
                listItems.add("a")
                listItems.add("b")
                listItems.add("c")
                listItems.add("d")
                listItems.add("e")
        
                //if you want to add array items to a list you can try this for each loop
                for(items in array)
                    listItems.add(items)
                
                //check the result in console
                Log.e("TAG","listItems array: $listItems")
    
            adapter = ListViewAdapter()
            adapter.updateList(listItems)
            adapter.notifyDataSetChanged()
        
            }
        }


//Here is the adapter class
    class ListviewAdapter : BaseAdapter(){
    
    private var itemsList = arrayListOf<String>()
    
    override fun getView(position: Int, container: View?, parent: ViewGroup?): View {
            var view  = container
            val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            if (view == null)
                view = inflater.inflate(R.layout.list_pc_summary, parent, false)
    
    return view
    }
    
    override fun getItem(position: Int): Any  = itemsList[position]
    
    override fun getItemId(position: Int): Long = position.toLong()
    
    override fun getCount(): Int = itemsList.size
    
    fun updateList(listItems: ArrayList<String>()){
        this.itemsList = listItems
        notifyDatSetChanged
    
    }
   
        }
       
    //Here I just explained two ways, we can do this many ways.

而不是

listItems.add("New Item");
adapter.notifyDataSetChanged();

您可以直接拨打

adapter.add("New Item");

简单的回答是:当你创建一个ListView时,你传递给它一个数据引用。 现在,无论何时该数据将被更改,它都会影响列表视图,因此在调用adapter.notifyDataSetChanged();之后,它将向列表视图中添加该项。

如果你正在使用RecyclerView,只更新最后一个元素(如果你已经在objs列表的末尾添加了它)来节省内存:

首先,您必须在activity_main.xml中添加一个ListView、一个EditText和一个按钮。

现在,在ActivityMain中:

private EditText editTxt;
private Button btn;
private ListView list;
private ArrayAdapter<String> adapter;
private ArrayList<String> arrayList;

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

    editTxt = (EditText) findViewById(R.id.editText);
    btn = (Button) findViewById(R.id.button);
    list = (ListView) findViewById(R.id.listView);
    arrayList = new ArrayList<String>();

    // Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
    // and the array that contains the data
    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    // Here, you set the data in your ListView
    list.setAdapter(adapter);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // this line adds the data of your EditText and puts in your array
            arrayList.add(editTxt.getText().toString());
            // next thing you have to do is check if your adapter has changed
            adapter.notifyDataSetChanged();
        }
    });
}

这对我有用,希望我帮到你了