如何将项目添加到列表视图

时间:2016-03-14 12:58:49

标签: android list listview

您好我是Android新手我想创建类似于此链接中给出的应用程序的应用程序 http://www.androiddom.com/2011/02/android-shopping-cart-tutorial.html?m=1 唯一不同的是,在目录活动中我没有列表视图,而是我有图像按钮。所以,我点击任何图像按钮,它转到产品详细信息活动(与链接中的示例相同)。其他活动与链接中的示例相同。

我想要的只是如果在目录活动中有图像按钮时使用按钮添加到购物车,如何将项目添加到列表视图。

请为我提供帮助。

1 个答案:

答案 0 :(得分:1)

主布局文件

<?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">

<ListView android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:id="@+id/mainListView">
</ListView>

活动文件

package com.example.android;

import java.util.ArrayList;
import java.util.Arrays;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SimpleListViewActivity extends Activity {

private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;

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

// Find the ListView resource. 
mainListView = (ListView) findViewById( R.id.mainListView );

// Create and populate a List of context names.
String[] context = new String[] { "context1", "context2", "context3", "context4","context5"};  
ArrayList<String> context = new ArrayList<String>();
contextList.addAll( Arrays.asList(context) );

// Create ArrayAdapter using the context list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, contextList);

// Add more contexts. If you passed a String[] instead of a List<String> 
// into the ArrayAdapter constructor, you must not add more items. 
// Otherwise an exception will occur.
listAdapter.add( "context8" );
listAdapter.add( "context9" );
listAdapter.add( "context10" );

// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );      
}
}