将新行添加到多列listview

时间:2014-03-09 08:05:04

标签: android android-layout listview android-listview

我是Android的新手,在我的应用程序中我有一个多列listview,我需要在按钮点击上添加新行或项目到listview ..我从这里尝试了很多解决方案,也来自很多网站但是我的问题没有解决我在这里附上我的代码请任何人帮助。

布局1(包括列表视图listOrders)

布局2(listview_row.xml)

<LinearLayout 
android:id="@+id/relativeLayout1" 
android:layout_height="fill_parent" 
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">



<TextView
    android:id="@+id/txtItem"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1.27"
    android:text="Item" >

</TextView>

<TextView
    android:id="@+id/txtQuantity"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1.12"
    android:text="Quantity" >

</TextView>

<TextView
    android:id="@+id/txtTotal"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Total"
    android:layout_weight="1">
</TextView>

主要活动

public class AddOrderActivity extends Activity implements View.OnClickListener 
{
private ListView list;
private ArrayList<HashMap<String, String>> mylist;
private HashMap<String, String> map;
SimpleAdapter mSchedule;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activityaddorder);   
Button btnAddItem = (Button) findViewById(R.id.btnAddItem);
btnAddItem.setOnClickListener(this);
list = (ListView) findViewById(R.id.listOrders);
mylist = new ArrayList<HashMap<String, String>>();
// used to show the heading of listview
map = new HashMap<String, String>();
map.put("txtItem", "Item");
map.put("txtQuantity", "Quantity");
map.put("txtTotal", "Total");
mylist.add(map);
mSchedule = new SimpleAdapter(AddOrderActivity.this, mylist, R.layout.listview_row,
new String[] { "txtItem", "txtQuantity", "txtTotal" }, new int[] {
R.id.txtItem, R.id.txtQuantity, R.id.txtTotal });
list.setAdapter(mSchedule); 
}

@Override
//i want to add new row on this button click
public void onClick(View v) {
map = null;
map.put("txtItem", "1");
map.put("txtQuantity", "2");
map.put("txtTotal", "2");
mylist.add(map);    
mSchedule.notifyDataSetChanged();   
finish();       
}
}   

标题是正确的,但是当我点击按钮时,应用程序将崩溃。

1 个答案:

答案 0 :(得分:0)

我在代码中看到了一些错误。试试这个。

@Override 
onClick(View v) { 
    map = new HashMap<String,String>();
    map.put("txtItem", "1");
    map.put("txtQuantity", "2"); 
    map.put("txtTotal", "2");
    mylist.add(map);    

    mSchedule = new SimpleAdapter(AddOrderActivity.this, mylist, R.layout.listview_row,new String[] { "txtItem", "txtQuantity", "txtTotal" }, new int[] {
R.id.txtItem, R.id.txtQuantity, R.id.txtTotal });  

    list.setAdapter(mSchedule); 
    } 
}

你不应该初始化map = null(你在该代码中获得了一个nullPointerException)

并且必须使用新Map重新设置适配器。

我希望它有效。