且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在列表视图中动态添加项目

更新时间:2023-11-29 22:23:58

为此仅使用下面给出的示例:
对于Instance,您将添加一些字符串添加到列表中

所以创建一个这样的ListArray

  ArrayList< String> listItems = new ArrayList< String>(); 

现在每当你想添加一些字符串到列表只是做这个事情

  EditText editText =(EditText)findViewById(R.id.edit); 
listItems.add(我的字符串); OR
listItems.add(editText.getText.toString()); //如果您从editText获取字符串值并将其添加到列表中,则会变为

使用此Xml内在main.xml中的线性布局

 < EditText android:id =@ + id / edit
android :layout_width =fill_parent
android:layout_height =wrap_content/>

现在,当您动态添加一个项目时,请调用此

  adapter.notifyDataSetChanged(); 

上面将更新您的列表并显示已更新的列表。



有关更多信息,请参阅以下链接:



http://www.androidpeople.com/android-custom-listview-tutorial-part-1

http://www.androidpeople.com/android-custom-listview-tutorial-part-2

http:/ /www.androidpeople.com/android-custom-dynamic-listview-%E2%80%93part3



在这些教程中,您可以将String []替换为ArrayList在答案顶部给出,当你想添加任何项目时,只需使用第二个代码片段。



感谢

sHaH


I want to make a dynamic list view which gets the user credentials when I login for the first time and displays it in a list the next time I start the app. I know how to send the username from one intent to another. i haven't focused on the SQLite part yet, will do that later. I'm facing problems in creating the dynamic list view. Found one very useful thread - Dynamically add elements to a listView Android

he used a button on the screen and called the method onClick to populate the list. Can i do it without the button? I want it to automatically happen once i am able to login. how can i use the statements in my code?

listItems.add(value);
adapter.notifyDataSetChanged();

here value is the username i am getting from some other intent.
please help. thanks!

For this Just use the example given below: For Instance you are Adding Some Strings into your List

So Create a ListArray like this

ArrayList<String> listItems = new ArrayList<String>();

now whenever you want to add certain string into list just do this thing

  EditText editText = (EditText) findViewById(R.id.edit);
  listItems.add("my string");  OR
  listItems.add(editText.getText.toString()); //incase if you are getting string value from editText and adding it into the list

Use this Xml inside your linear layout in main.xml

  <EditText android:id="@+id/edit"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"/>

Now when you have added one item dynamically then call this

  adapter.notifyDataSetChanged();

The above will update your list and display the upadted list.

For more info about this see the following links:

http://www.androidpeople.com/android-custom-listview-tutorial-part-1
http://www.androidpeople.com/android-custom-listview-tutorial-part-2
http://www.androidpeople.com/android-custom-dynamic-listview-%E2%80%93part3

In these tutorials you can replace String[] with ArrayList as given at the top of the answer ook and when you want to add any item just simply use the second code snippet.

Thanks
sHaH