Android - 添加 ArrayList 中的项目后动态更新自定义 ListView [英] Android - Dynamically Updating a custom ListView after items in an ArrayList are added

查看:25
本文介绍了Android - 添加 ArrayList 中的项目后动态更新自定义 ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,它显示从 ArrayList 中获取的最初填充的自定义 ListView,然后用户可以将其添加到我存储没有问题的列表中.我在显示添加的项目时遇到问题.到目前为止,我在网上看到的代码使用 ArrayAdapter,它们只使用简单的 listView 而不是自定义的.

I have an activity that displays an initially populated custom ListView taken from an ArrayList, the user can then add to this list which I have no problem storing. I'm having problems displaying the added items. So far, the codes I see online use ArrayAdapter and they're only using the simple listView and not a custom one.

相关文件如下:

list_row_layout.xml

list_row_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent" >

  <TextView
    android:id="@+id/variant"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="variant" />

  <TextView
    android:id="@+id/quantity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="quantity" />

  <TextView
    android:id="@+id/unit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginRight="221dp"
    android:layout_toLeftOf="@+id/quantity"
    android:text="unit" />

</RelativeLayout>

这是我的 activity_order_form.xml 中包含 listView 元素的部分.

Here is the part in my activity_order_form.xml that has the listView element.

<RelativeLayout
    android:id="@+id/relativeLayout3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/relativeLayout2"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textViewVariantB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="94dp"
        android:text="Variant"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textViewUnit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="123dp"
        android:text="Unit"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <ListView
        android:id="@+id/listViewProductOrder"
        android:layout_width="match_parent"
        android:layout_height="350dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textViewVariantB" >

    </ListView>
</RelativeLayout>

这里是存放ArrayList的类.

Here is the class where the ArrayList are stored.

public class CurrentOrderClass {

  private String productName;

  //ArrayLists
  private ArrayList<String> variantArray = new ArrayList<String>();
  private ArrayList<String> unitArray = new ArrayList<String>();
  private ArrayList<Integer> quantityArray = new ArrayList<Integer>();


  //TODO ArrayList functions
  public ArrayList<String> getUnitArray() {
    return unitArray;
  }

  public void setUnitArray(ArrayList<String> unitArray) {
    this.unitArray = unitArray;
  }

  public void addToUnitArray(String unit){
    this.unitArray.add(unit);
  }



  public ArrayList<Integer> getQuantityArray() {
    return quantityArray;
  }

  public void setQuantityArray(ArrayList<Integer> quantityArray) {
    this.quantityArray = quantityArray;
  }

  public void addToQuantityArray(int quantity){
    this.quantityArray.add(quantity);
  }



  public ArrayList<String> getVariantArray() {
    return variantArray;
  }

  public void setVariantArray(ArrayList<String> variantArray) {
    this.variantArray = variantArray;
  }

  public void addToVariantArray(String variantArray){
    this.variantArray.add(variantArray);
  }
}

这是 CustomListAdapter.java 文件

Here is the CustomListAdapter.java file

public class CustomListAdapter extends BaseAdapter {

  private ArrayList<CurrentOrderClass> listData;

  private LayoutInflater layoutInflater;

  public CustomListAdapter(Context context, ArrayList<CurrentOrderClass> listData) {
    this.listData = listData;
    layoutInflater = LayoutInflater.from(context);
  }

  @Override
  public int getCount() {
    return listData.size();
  }

  @Override
  public Object getItem(int position) {
    return listData.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
        holder = new ViewHolder();
        holder.variantView = (TextView) convertView.findViewById(R.id.variant);
        holder.unitView = (TextView) convertView.findViewById(R.id.unit);
        holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString());
    holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString());
    holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));

    return convertView;
}

  static class ViewHolder {
    TextView variantView;
    TextView unitView;
    TextView quantityView;
  }


}

这是我的 OrderForm.java 活动的一部分,它显示了 onCreate 和填充 listView 的方法,以及获取用户输入的部分.

This is part of my OrderForm.java activity, this shows the onCreate and the method that populates the listView, as well as the part where user input is taken.

public class OrderForm extends Activity {

  public TextView tv;
  private int variantPosition; 
  CustomListAdapter customListAdapter;
  CurrentOrderClass currentOrder = new CurrentOrderClass();

  @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_order_form);
          tv = (TextView)findViewById(R.id.textViewProduct);

          //set variants here
          popolateItem();

          //set current order listview here
          ArrayList image_details = getListData();
          final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder);

          customListAdapter = new CustomListAdapter(this, image_details);
          lv1.setAdapter(customListAdapter);

  }

  private ArrayList getListData() {

          ArrayList results = new ArrayList();

          for(int i = 0; i < 10; i++){
        currentOrder.getQuantityArray().add(i);
        currentOrder.getUnitArray().add("Sample text here." + i);
        currentOrder.getVariantArray().add("Another sample text here" + i);
        results.add(currentOrder);
          }
          return results;

  }

      //....snip snip excess code.....
      //This is the part wherein I add new items to the ArrayList in the class
      //After this, I'm not sure how to proceed


  currentOrder.setProductName(product.getName());
  currentOrder.addToQuantityArray(newQuantity);
  currentOrder.addToUnitArray(product.getUnit()[position]);
  currentOrder.addToVariantArray(product.getVariant()[variantPosition]);

  Log.d("Angelo", currentOrder.getProductName() + " " 
            + currentOrder.getQuantityArray() + " " 
            + currentOrder.getUnitArray() + " "
            + currentOrder.getVariantArray());


}

我还尝试将 customListAdapter.notifyDataSetChanged(); 放在日志条目之后,但没有任何反应.任何人的想法?谢谢.

I also tried to place customListAdapter.notifyDataSetChanged(); after the Log entry but nothing happened. Any ideas anyone? Thanks.

在回答和修改后进行编辑.

只需按照下面 FD 的回答并添加他在那里指定的函数和之后的 2 个函数调用.现在,您想像这样修改 getListData() 函数:

Just follow FD's answer below and add the function he specified there and the 2 function calls after that. Now, you want to modify your getListData() function like this:

private ArrayList getListData() {

    ArrayList results = new ArrayList();

    int loopUntil;

    /* Two scenarios
     * First ---> the user started the activity for the first time, which means that the pre-populated list is what we want
     *            if this is the case, look at the else part of the boolean statement, it only loops until 10 
     *            and in addition, populates those elements
     * Second ---> the user has set something already and we want to populate until that element.
     * 
     */


    if(currentOrder.getQuantityArray().size() > 10){
        loopUntil = currentOrder.getQuantityArray().size();

        for(int i = 0; i < loopUntil; i++){
            currentOrder.getQuantityArray();
            currentOrder.getUnitArray();
            currentOrder.getVariantArray();
            results.add(currentOrder);
        }

    }
    else{
        loopUntil = 10;

        for(int i = 0; i < loopUntil; i++){
            currentOrder.getQuantityArray().add(i);
            currentOrder.getUnitArray().add("Sample text here." + i);
            currentOrder.getVariantArray().add("Another sample text here" + i);
            results.add(currentOrder);
        }
    }

    return results;

}

第一个条件在存在超出预填充的项目时执行,因为 else 语句仅循环到预填充的项目(项目编号 9,索引 0).此循环确保您添加到 ArrayList 的所有内容都会添加到 ListView.

The first condition executes when there is an item beyond the pre-populated one, since the else statement loops only until the pre-populated item (item number 9, index 0). This loop ensures that everything you add to the ArrayList gets added to the ListView.

第二个条件在第一次打开 Activity 时执行,除了您自己填充的列表之外,该列表中应该没有任何内容.

The second condition executes when the activity is opened for the first time and there's supposed to be nothing in that list yet except the ones that you populated yourself.

推荐答案

您的适配器没有获得新数据,因为您正在使用它自己的一组数据对其进行初始化.

Your adapter does not get the new data, because you are initializing it with its own set of data.

一种可能性是实例化一个新的适配器并将其分配给 ListView.

One possibility would be to instantiate a new adapter and assign it to the ListView.

在您的活动中为您的 ListView 添加一个字段:

Add a field for your ListView in your activity:

public TextView tv;
private int variantPosition; 
CustomListAdapter customListAdapter;
CurrentOrderClass currentOrder = new CurrentOrderClass();
ListView myListView; //Listview here

在 onCreate 中,将 myListView 设置为指向您的 ListView:

In onCreate, set myListView to point to your ListView:

final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder)
myListView = lv1;

最后,当你改变你的数据时,为新数据创建一个新的Adapter:

Finally, when you change your data, create a new Adapter for the new data:

myListView.setAdapter(new CustomListAdapter(this, getListData());

或者,修改您的自定义适配器以包含 setListData 方法:

Alternatively, modify your Custom adapter to contain a setListData method:

public class CustomListAdapter extends BaseAdapter {

  private ArrayList<CurrentOrderClass> listData;

  private LayoutInflater layoutInflater;

  public CustomListAdapter(Context context, ArrayList<CurrentOrderClass> listData) {
    this.listData = listData;
    layoutInflater = LayoutInflater.from(context);
  }

  public void setListData(ArrayList<CurrentOrderClass> data){
    listData = data;
  }

  @Override
  public int getCount() {
    return listData.size();
  }


  @Override
  public Object getItem(int position) {
    return listData.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
        holder = new ViewHolder();
        holder.variantView = (TextView) convertView.findViewById(R.id.variant);
        holder.unitView = (TextView) convertView.findViewById(R.id.unit);
        holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString());
    holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString());
    holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));

    return convertView;
}

  static class ViewHolder {
    TextView variantView;
    TextView unitView;
    TextView quantityView;
  }


}

然后,修改数据后,只需调用:

Then, after modifying your data, just call:

customListAdapter.setListData(getListData());
customListAdapter.notifyDataSetChanged();

这篇关于Android - 添加 ArrayList 中的项目后动态更新自定义 ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆