Android listView 动态添加项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1998483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:08:46  来源:igfitidea点击:

listView dynamic add item

androidlistview

提问by pengwang

I used ListViewto dynamic add item,but there is a problem about not Smooth add. there are textView and button in my listActivity,Iwant to Press button ,then TextView's text can auto add to ListView,but i Pressed button, it donot work,unless after i enter content , press "OK"Key ,then Pressed button, TextView'stext can auto add to ListView. I donot know why. If I continuous Pressed button, as 3 times, then press "Ok" key, the content

ListView以前是动态添加item的,但是出现了不能平滑添加的问题。我的列表活动中有 textView 和按钮,我想按下按钮,然后TextView文本可以自动添加到ListView,但是我按下按钮,它不起作用,除非我输入内容后,按“确定”键,然后按下按钮,TextView's文本可以自动添加到ListView. 我不知道为什么。如果我连续按下按钮,为3次,然后按“确定”键,内容

auto add list

自动添加列表

View but 3 times.

查看但 3 次。

 public class DynamicListItems extends ListActivity {
   private static final String   ITEM_KEY   = "key";
   ArrayList<HashMap<String, String>>   list= new ArrayList<HashMap<String, String>>();
private SimpleAdapter   adapter;
private EditText    newValue;@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.dynamic_list);
    newValue = (EditText) findViewById(R.id.new_value_field);

    setListAdapter(new SimpleAdapter(this, list, R.layout.row, new String[] { ITEM_KEY }, new int[] { R.id.list_value }));
    ((ImageButton) findViewById(R.id.button)).setOnClickListener(getBtnClickListener());
}

private OnClickListener getBtnClickListener() {
    return new OnClickListener() {
        public void onClick(View view) {
            try {

                HashMap<String, String> item = new HashMap<String, String>();
                item.put(ITEM_KEY, newValue.getText().toString());
                list.add(item);

                adapter.notifyDataSetChanged();
            } catch (NullPointerException e) {
                Log.i("[Dynamic Items]", "Tried to add null value");
            }
        }
    };
   }}

How to dynamic delete the item ?

如何动态删除项目?

  • dynamic_list.xml only contains listView ,button,textView
  • row.xml contains TextView
  • dynamic_list.xml 只包含 listView ,button,textView
  • row.xml 包含 TextView

回答by Dwivedi Ji

notifyDataSetChanged()method is used to update the adapter.

notifyDataSetChanged()方法用于更新适配器。

Here I am posting a working answer steps by step.

在这里,我将逐步发布一个有效的答案。

First of main.xmlfile :

首先main.xml中的文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" 
        android:id="@+id/input">

        <EditText
            android:id="@+id/editText_input"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:text="Add" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_above="@+id/input"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listView_items"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </ListView>

    </LinearLayout>

</RelativeLayout>

Here MainActivity.java:

这里MainActivity.java

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {
    private EditText etInput;
    private Button btnAdd;
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dyanamic_list);
        setUpView();

    }

    private void setUpView() {
        etInput = (EditText)this.findViewById(R.id.editText_input);
        btnAdd = (Button)this.findViewById(R.id.button_add);
        lvItem = (ListView)this.findViewById(R.id.listView_items);

        itemArrey = new ArrayList<String>();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
        lvItem.setAdapter(itemAdapter);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                addItemList();
            }
        });

        etInput.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    addItemList();
                }
                return true;
            }
        });
    }

    protected void addItemList() {
        if (isInputValid(etInput)) {
            itemArrey.add(0,etInput.getText().toString());
            etInput.setText("");
            itemAdapter.notifyDataSetChanged();
        }   
    }

    protected boolean isInputValid(EditText etInput2) {
        if (etInput2.getText().toString().trim().length()<1) {
            etInput2.setError("Please Enter Item");
            return false;
        } else {
            return true;
        }
    }
}

回答by Ryan Alford

Is your getBtnClickListenermethod part of the ListActivityor ArrayAdapterclass?

你的getBtnClickListener方法是ListActivityorArrayAdapter类的一部分吗?

For me, when I update from the ListActivityclass, I use this code...

对我来说,当我从ListActivity课堂上更新时,我使用这个代码......

// code to add a Contact to my database
// code to add a Contact to the list that
//   that is used by the ListView
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);

When I am updating from a method inside the ArrayAdapterclass, I use this code...

当我从ArrayAdapter类中的方法更新时,我使用此代码...

 // from a LongPress on a ListView item
 convertView.setOnLongClickListener(new OnLongClickListener(){
     @Override
     public boolean onLongClick(View view) {
         view.performHapticFeedback(0, View.HAPTIC_FEEDBACK_ENABLED);
         // code to remove a Contact name from my database
         // code to remove that Contact name from my list
         //    that is used by the ListView
         ContactsAdapter.this.notifyDataSetChanged();
         return true;
     });

回答by Tai Tran

I use a thread to add more data to my list in background and then notifydatasetchange, It work successfully

我使用一个线程在后台将更多数据添加到我的列表中,然后notifydatasetchange它成功运行

Here are complete code : http://code.google.com/p/dynamic-listview/source/checkout

这里是完整的代码:http: //code.google.com/p/dynamic-listview/source/checkout

回答by Mario Alzate

Yes!!, the method notifyDataSetChanged() applied in the ArrayAdapter before you fulling him, was the solution for me. Reading from Firebase.

是的!!,在你填满他之前在 ArrayAdapter 中应用的方法 notifyDataSetChanged() 是我的解决方案。从 Firebase 读取。

Objects

对象

    private DatabaseReference myRef;
    ArrayList<String> lista;
    ArrayAdapter<String> adapter;

OnCreate

在创建

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myRef = database.getReference("chat");

    //GETTIN MY DATA TO SHOW IN CHAT
    lista = new ArrayList<String>();

OnResume

在恢复

    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnappy : dataSnapshot.getChildren()){
                for (DataSnapshot rePostSnappy : postSnappy.getChildren()){
                    // Defined Array values to show in ListView
                    lista.add(new String(rePostSnappy.getValue().toString()));
                    adapter.notifyDataSetChanged();//Notyfing adapter that will goes to change
                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, lista);

    ListView listVista = (ListView) findViewById(R.id.list);
    listVista.setAdapter(adapter);