android:
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="放入購物車" />
<TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1" />
<TextView
android:id="@+id/TextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/TextView1" />
<ListView
android:id="@+id/lstView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/TextView2" />
</RelativeLayout>
-----------------------------------------------
java:
package com.example.test18;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener,
OnItemClickListener {
public Button btn1;
public TextView txtView1, txtView2;
public ListView lis;
String[] str = new String[] { "香蕉", "西瓜", "梨子", "水蜜桃" };
String[] b = new String[] { "330", "120", "250", "280" };
int[] a = new int[] { 330, 120, 250, 280 };
int i;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lis = (ListView) findViewById(R.id.lstView);
txtView1 = (TextView) findViewById(R.id.TextView1);
txtView2 = (TextView) findViewById(R.id.TextView2);
(btn1 = (Button) findViewById(R.id.button1)).setOnClickListener(this);
ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, str);
lis.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lis.setAdapter(arrayadapter);
i = arrayadapter.getCount();
lis.setOnItemClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
int sellAll = 0;
for (int x = 0; x < i; x++)
if (lis.isItemChecked(x))
sellAll += a[x];
txtView2.setText("總額:" + sellAll);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
if (lis.isItemChecked(arg2)) {
String sel = arg0.getItemAtPosition(arg2).toString();
setTitle("選購了:" + sel);
} else {
setTitle("");
}
}
}