2013-12-05 2 views
0

Я довольно новичок в разработке Java и Android. В настоящее время я создаю приложение для покупок и смотрю на добавление кнопки «Удалить» в список «Моя корзина».Добавление кнопки удаления в мой список товаров

Вот мой текущий код для моей деятельности по списку для моей корзины покупок, я не совсем уверен, с чего начать, и некоторые рекомендации будут очень признательны.

Благодаря

package .shopper; 

import java.util.List; 

import android.os.Bundle; 
import android.app.Activity; 
import android.app.ListActivity; 
import android.content.Context; 
import android.content.Intent; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.ImageView; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.support.v4.app.NavUtils; 

public class CartListActivity extends ListActivity { 

    public class ProductListAdapter extends BaseAdapter { 

     private final Context context; 

     private List<Product> itemList; 

     public List<Product> getItemList() { 
      return itemList; 
     } 

     public void setItemList(List<Product> itemList) { 
      this.itemList = itemList; 
     } 

     public Context getContext() { 
      return context; 
     } 

     public ProductListAdapter(Context c) { 
      context = c; 
     } 

     @Override 
     public int getCount() { 
      if(itemList == null) return 0; 
      else return itemList.size(); 
     }  

     @Override 
     public Object getItem(int position) { 
      if (itemList == null) return null; 
      else return itemList.get(position); 
     } 

     @Override 
     public long getItemId(int position) { 
      if (itemList == null) return 0; 
      else return itemList.get(position).hashCode(); 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      View cell = convertView; 

      if (cell == null) { 
       // get layout from mobile xml 
       LayoutInflater inflater = ((Activity)context).getLayoutInflater(); 
       cell = inflater.inflate(R.layout.adapter_product_list, parent, false); 
      } 

      Product p = itemList.get(position); 

      //set value into textview according to position 
      TextView textView = (TextView) cell.findViewById(R.id.product_title); 
      textView.setText(p.getProductName()); 

      // add £ symbol 
      textView = (TextView) cell.findViewById(R.id.product_info); 
      textView.setText("Price: " + "£"+ p.getPrice()); 

      //set value into imageview according to position 
      ImageView imgView = (ImageView) cell.findViewById(R.id.product_image); 
      // clear the image 
      imgView.setImageDrawable(null); 
      //and load from the network 
      p.loadImage(imgView, 54, 54);   

      return cell; 
     } 

    } 

    public static final Integer[] productIcons = { 
     0, // index 0 is empty 
     R.drawable.books, 
     R.drawable.films, 
     R.drawable.music, 
     R.drawable.games, 
    }; 

    private int categoryId; 
    private ProductListAdapter adapter; 
    private ListViewLoader loader; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // get the category from the intent 
     Intent intent = getIntent(); 
     categoryId = intent.getIntExtra(MainActivity.SELECTED_CATEGORY, 0); 

     adapter = new ProductListAdapter(this); 
     setListAdapter(adapter); 

     // Show the Up button in the action bar. 
     setupActionBar(); 

     loader = new ListViewLoader(adapter, categoryId); 
     loader.execute(String.format(MainActivity.WEBSERVER_GETLIST, categoryId)); 
    } 

    /** 
    * Set up the {@link android.app.ActionBar}. 
    */ 
    private void setupActionBar() { 

     getActionBar().setDisplayHomeAsUpEnabled(true); 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.product_list, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case R.id.show_cart: 
      //create the intent for the cart activity 
      Intent intent = new Intent(getApplicationContext(), CartActivity.class); 
      startActivity(intent); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
     //create an intent 
     Intent intent = new Intent(this, ProductActivity.class); 
     Product p = (Product)adapter.getItem(position); 
     //specify the extra parameters we want to pass 
     intent.putExtra(MainActivity.SELECTED_CATEGORY, p.getCategoryId()); 
     intent.putExtra(MainActivity.SELECTED_PRODUCTID, p.getProductId()); 
     intent.putExtra(MainActivity.SELECTED_PRODUCTNAME, p.getProductName()); 
     intent.putExtra(MainActivity.SELECTED_PRODUCTPRICE, p.getPrice()); 
     intent.putExtra(MainActivity.SELECTED_SUITABLEFORKIDS, p.getSuitableForKids()); 

     startActivity(intent); 
    } 

} 

EDIT: XML для adapter_product_list

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="8dp"> 
    <ImageView 
     android:id="@+id/product_image" 
     android:layout_width="54dp" 
     android:layout_height="54dp" 
     android:padding="5dp" 
     android:layout_alignParentLeft="true" /> 
    <TextView 
     android:id="@+id/product_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_toRightOf="@+id/product_image" 
     android:layout_alignTop="@+id/product_image" 
     android:textColor="#446688" 
     android:textSize="20sp" /> 
    <TextView 
     android:id="@+id/product_info" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_toRightOf="@+id/product_image" 
     android:layout_below="@+id/product_title" 
     android:textColor="#777777" 
     android:textSize="16sp" 
     android:textStyle="italic" /> 


</RelativeLayout> 
+0

Тогда что проблема объясняет? – keshav

+0

Я не уверен, как реализовать кнопку удаления ... спасибо – user3070626

ответ

0

1) надежда p.loadImage (imgView, 54, 54); выполняется в asyncTask 2) если вы хотите щелкнуть по кнопке в строке ListView, то вы можете добавить кнопку в свой макет строки и внедрить onClickListenr этой кнопки в свой метод getView для адаптера.in onClick yous hould есть:

if(position<itemList.size()){ 
     //TO REMOVE TEM FROM ARRAY LIST 
     itemList.remove(position); 
     //TO Update the ListView 
     notifyDataSetChanged(); 
} 

вы можете реализовать многоступенчатую линии удалить, добавив флажок в вашем listRow и добавлении positon элемента для удаления к ArrayList из Целых и после щелчка ИНГ кнопки удаления вы должны удалить все элементы из imteList и после этого вызова notifyDataSetChanged()

EDIT

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:padding="8dp"> 
<ImageView 
    android:id="@+id/product_image" 
    android:layout_width="54dp" 
    android:layout_height="54dp" 
    android:padding="5dp" 
    android:layout_alignParentLeft="true" /> 
<TextView 
    android:id="@+id/product_title" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_toRightOf="@+id/product_image" 
    android:layout_alignTop="@+id/product_image" 
    android:textColor="#446688" 
    android:textSize="20sp" /> 
<TextView 
    android:id="@+id/product_info" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_toRightOf="@+id/product_image" 
    android:layout_below="@+id/product_title" 
    android:textColor="#777777" 
    android:textSize="16sp" 
    android:textStyle="italic" /> 
<Button 
    android:id="@+id/deleteBtn" 
    android:layout_width="wrap_content 
    android:layout_height="wrap_content" 
    android:layout_toRightOf="@+id/product_info" 
</RelativeLayout> 

вы должны добавить эту кнопку в макете, а в GetView метод адаптера добавить

Button delete=v.findViewById(R.id.deleteBtn); 
delete.setOnClickListener(new View.OnClickListener(){ 
     @Override 
    public void onClick(View v) { 
     //THE PART I WROTE ABOVE 
    }  
}) 
+0

Спасибо за ответ, p.loadImage запускает asynctask. Добавление кнопки к макету и реализация onClickListener в порядке, я помещаю код выше в метод onListItemClick? спасибо, я получаю ошибки. – user3070626

+0

в вашем классе getItem() класса Adapter, вы должны добавить onClickListener для кнопки, которую вы будете использовать для удаления строки. – Eddy

+0

Спасибо за всю помощь и изменения, я ценю ваше время. Я помещаю код, который вы мне дали в конце getView (и я пробовал другие места в getView), но я получаю много ошибок, таких как Button и v не могут быть разрешены. Еще раз спасибо – user3070626

1

Изменение XML как следующее

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:padding="8dp" > 

    <ImageView 
     android:id="@+id/product_image" 
     android:layout_width="54dp" 
     android:layout_height="54dp" 
     android:layout_alignParentLeft="true" 
     android:padding="5dp" 
     android:src="@drawable/ic_launcher" /> 

    <TextView 
     android:id="@+id/product_title" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignTop="@+id/product_image" 
     android:layout_toRightOf="@+id/product_image" 
     android:text="adjkajdjk" 
     android:textColor="#446688" 
     android:textSize="20sp" /> 

    <TextView 
     android:id="@+id/product_info" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@+id/product_title" 
     android:layout_toRightOf="@+id/product_image" 
     android:text="adjkajdjk" 
     android:textColor="#777777" 
     android:textSize="16sp" 
     android:textStyle="italic" /> 

    <Button 
     android:id="@+id/delete_btn" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:text="Delete" /> 

</RelativeLayout> 

И в адаптере внутри GetView() функцию добавьте это

Button deleteBtn = (Button) findViewById(R.id.delete_btn); 
     deleteBtn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) 
      { 
       itemList.remove(position); 
       notifyDataSetChanged(); 

      } 
     }); 
Смежные вопросы