Add a Button to a ListView for each Element

对着背影说爱祢 提交于 2020-01-25 11:03:32

问题


I am creating a shopping cart app and I am trying to populate a String[] Product which is called items. Each item has an ID a Name and a Price. The issue I am having is that I am trying to make a custom ListView but I can not get it to run on my android device. It keeps crashing every time I use a customer ListView. Maybe I am not doing it right or I need to create a customer adapter as well? I have tried these methods but neither were successful. Here is what I have, I currently am using the simple_list_item_check layout but I just implemented that to see if it would work, in which that does. The android simple layouts do, but my custom won't. Can anyone lead me in the right direction?

CustomerView.activity

    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.Toast;
    import android.widget.CheckedTextView;


    public class CustomerView extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_customer_view);

    Product[] items = {
            new Product(1, "Milk", 21.50),
            new Product(2, "Butter", 15.99),
            new Product(3, "Yogurt", 14.90),
            new Product(4, "Toothpaste", 7.99),
            new Product(5, "Ice Cream", 10.00),

    };

    final ListAdapter theAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_checked, items);

    ListView customerlist = (ListView) findViewById(R.id.customerList);
    customerlist.setTextFilterEnabled(true);
    customerlist.setAdapter(theAdapter);
    customerlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            CheckedTextView check = (CheckedTextView)view;
            check.setChecked(!check.isChecked());
            String itemselected = "You Touched " +
                  String.valueOf(theAdapter.getItem(position));

            Toast.makeText(CustomerView.this, itemselected, Toast.LENGTH_SHORT).show();

        }
    });

}





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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Product.java

    public class Product {

private int id;
private String name;
private double price;
private boolean selected;


public Product(int id, String name, double price) {
    this.id = id;
    this.name = name;
    this.price = price;

}

@Override
public String toString() {
    return this.id + " " + this.name + " [$" + this.price + "]";
}
}

row_layout.xml

    <LinearLayout 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"
android:orientation="horizontal"
tools:context="shoppingcart.cop4331.com.shoppingcart.CustomerView">


<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add to Cart"
    android:gravity="right"
    />


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textview1"
    android:textSize="20sp"/>



    </LinearLayout>

回答1:


Change line:

final ListAdapter theAdapter = new ArrayAdapter<>(this,
        android.R.layout.simple_list_item_checked, items);

to:

final ListAdapter theAdapter = new ArrayAdapter<>(this,
           R.layout.row_layout , R.id.textview1, items);

You use wrong ArrayAdapter constructor :) If root view is not a TextView (in your case root view is LinearLayout) you have to pass TextView id       




回答2:


You need to implement a ProductsAdapter. The ArrayAdapter constructor you are using is trying to set a list of only check item layouts which is invalid given your product. You will have to create a simple adapter which maps each variable in the Product object to the row_layout.xml.

You can model your adapter after this - https://github.com/ucsunil/receipts/blob/master/app/src/main/java/com/amex/receipts/adapters/ItemsAdapter.java. It is from a practice project I did sometime back which was to add items to a cart. You basically will override the getView() method to bind your views.




回答3:


I would create a custom adapter class, and within that adapter class have a callback. You can modify this code to take a String[] or ArrayList and also use your XML Layout.

This sample code is somewhat overkill, but it is the best I could do for providing an example right now.

public class WorkoutCardsAdapter extends ArrayAdapter<WorkoutView> {

private LayoutInflater mInflater;
String TAG = WorkoutCardsAdapter.class.getCanonicalName();
Callback mCallback;
List<WorkoutView> mViews;

public WorkoutCardsAdapter(Context context, List<WorkoutView> views, Callback callback) {
    super(context, 0, views);
    mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mCallback = callback;
    this.mViews = views;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;
    WorkoutView workoutView = getItem(position);
    convertView = null;


    if (convertView == null) {
        holder = new ViewHolder();
        if (workoutView.getWorkoutMainCategory().equals("Traditional")) {
            if (workoutView.getWorkoutType().equals("Strength")) {
                if (workoutView.getWorkoutCategory().equals("Weightlifting")) {
                    convertView = mInflater.inflate(R.layout.single_workout_layout_traditional_weights, parent, false);
                    holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                    holder.tvWorkoutCategory = (TextView) convertView.findViewById(R.id.textViewWorkoutCategoryItem);
                    holder.tvSetsItem = (TextView) convertView.findViewById(R.id.textViewSetsItem);
                    holder.tvRepsItem = (TextView) convertView.findViewById(R.id.textViewRepsItem);
                    holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                    holder.tvWorkoutWeight = (TextView) convertView.findViewById(R.id.textViewWorkoutWeightItem);
                    holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
                    convertView.setTag(holder);
                } else if (workoutView.getWorkoutCategory().equals("Isometric") || workoutView.getWorkoutCategory().equals("Circuit") ||
                        workoutView.getWorkoutCategory().equals("Other")) {
                    convertView = mInflater.inflate(R.layout.single_workout_layout_traditional_strength, parent, false);
                    holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                    holder.tvWorkoutCategory = (TextView) convertView.findViewById(R.id.textViewWorkoutCategoryItem);
                    holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                    holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                    holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
                    convertView.setTag(holder);
                }
            } else if (workoutView.getWorkoutType().equals("Endurance")){
                if(workoutView.getWorkoutCategory().equals("Running")){
                    convertView = mInflater.inflate(R.layout.single_workout_layout_traditional_endurance, parent, false);
                    holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                    holder.tvWorkoutCategory = (TextView) convertView.findViewById(R.id.textViewWorkoutCategoryItem);
                    holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                    holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                    holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);

                } else if (workoutView.getWorkoutCategory().equals("Other")){
                   convertView = mInflater.inflate(R.layout.single_workout_layout_traditional_endurance, parent, false);
                    holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                    holder.tvWorkoutCategory = (TextView) convertView.findViewById(R.id.textViewWorkoutCategoryItem);
                    holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                    holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                    holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
                }
            } else if (workoutView.getWorkoutType().equals("Other")){
                convertView = mInflater.inflate(R.layout.single_workout_layout_traditional_other, parent, false);
                holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
            }
        } else if (workoutView.getWorkoutMainCategory().equals("CrossFit")) {
            //TODO: DEFINE CROSSFIT
            if(workoutView.getWorkoutType().equals("For Reps & Time")){
                convertView = mInflater.inflate(R.layout.single_workout_layout_crossfit_repstime, parent, false);
                holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                holder.tvSetsItem = (TextView) convertView.findViewById(R.id.textViewSetsItem);
                holder.tvRepsItem = (TextView) convertView.findViewById(R.id.textViewRepsItem);
                holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
            } else if (workoutView.getWorkoutType().equals("For Reps")){
                convertView = mInflater.inflate(R.layout.single_workout_layout_crossfit_reps, parent, false);
                holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                holder.tvSetsItem = (TextView) convertView.findViewById(R.id.textViewSetsItem);
                holder.tvRepsItem = (TextView) convertView.findViewById(R.id.textViewRepsItem);
                holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);

            } else if (workoutView.getWorkoutType().equals("For Time")){
                convertView = mInflater.inflate(R.layout.single_workout_layout_crossfit_time, parent, false);
                holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                holder.tvSetsItem = (TextView) convertView.findViewById(R.id.textViewSetsItem);
                holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
            } else if (workoutView.getWorkoutType().equals("For Weight")){
                convertView = mInflater.inflate(R.layout.single_workout_layout_crossfit_weight, parent, false);
                holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                holder.tvSetsItem = (TextView) convertView.findViewById(R.id.textViewSetsItem);
                holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
            } else if (workoutView.getWorkoutType().equals("Other")){
                convertView = mInflater.inflate(R.layout.single_workout_layout_traditional_other, parent, false);
                holder.tvWorkoutType = (TextView) convertView.findViewById(R.id.textViewWorkoutTypeItem);
                holder.tvWorkoutName = (TextView) convertView.findViewById(R.id.textViewWorkoutName);
                holder.tvDescription = (TextView) convertView.findViewById(R.id.textViewWorkoutDescriptionItem);
                holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
            }

        }
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    if (workoutView.getWorkoutMainCategory().equals("Traditional")) {
        if (workoutView.getWorkoutType().equals("Strength")) {
            if (workoutView.getWorkoutCategory().equals("Weightlifting")) {
                holder.tvWorkoutName.setText(workoutView.getWorkoutName());
                holder.tvWorkoutType.setText(workoutView.getWorkoutType());
                holder.tvWorkoutCategory.setText(workoutView.getWorkoutCategory());
                holder.tvWorkoutWeight.setText(workoutView.getWorkoutWeight());
                holder.tvSetsItem.setText(workoutView.getSets());
                holder.tvRepsItem.setText(workoutView.getReps());
            } else if (workoutView.getWorkoutCategory().equals("Isometric") || workoutView.getWorkoutCategory().equals("Circuit") ||
                    workoutView.getWorkoutCategory().equals("Other")) {
                holder.tvWorkoutName.setText(workoutView.getWorkoutName());
                holder.tvWorkoutType.setText(workoutView.getWorkoutType());
                holder.tvWorkoutCategory.setText(workoutView.getWorkoutCategory());
                holder.tvDescription.setText(workoutView.getWorkoutDesc());
            }
        } else if (workoutView.getWorkoutType().equals("Endurance")){
            if(workoutView.getWorkoutCategory().equals("Running")){
                holder.tvWorkoutName.setText(workoutView.getWorkoutName());
                holder.tvWorkoutType.setText(workoutView.getWorkoutType());
                holder.tvWorkoutCategory.setText(workoutView.getWorkoutCategory());
                holder.tvDescription.setText(workoutView.getWorkoutDistance());
            } else if (workoutView.getWorkoutCategory().equals("Other")){
                holder.tvWorkoutName.setText(workoutView.getWorkoutName());
                holder.tvWorkoutType.setText(workoutView.getWorkoutType());
                holder.tvWorkoutCategory.setText(workoutView.getWorkoutCategory());
                holder.tvDescription.setText(workoutView.getWorkoutDesc());
            }
        } else if (workoutView.getWorkoutType().equals("Other")){
            holder.tvWorkoutName.setText(workoutView.getWorkoutName());
            holder.tvWorkoutType.setText(workoutView.getWorkoutType());
            holder.tvDescription.setText(workoutView.getWorkoutDesc());
        }
    } else if (workoutView.getWorkoutMainCategory().equals("CrossFit")) {
        //TODO: DEFINE CROSSFIT
        if(workoutView.getWorkoutType().equals("For Reps & Time")){
            holder.tvWorkoutName.setText(workoutView.getWorkoutName());
            holder.tvWorkoutType.setText(workoutView.getWorkoutType());
            holder.tvSetsItem.setText(workoutView.getWorkoutTime());
            holder.tvRepsItem.setText(workoutView.getReps());
            holder.tvDescription.setText(workoutView.getWorkoutDesc());
        } else if (workoutView.getWorkoutType().equals("For Reps")){
            holder.tvWorkoutName.setText(workoutView.getWorkoutName());
            holder.tvWorkoutType.setText(workoutView.getWorkoutType());
            holder.tvSetsItem.setText(workoutView.getSets());
            holder.tvRepsItem.setText(workoutView.getReps());
            holder.tvDescription.setText(workoutView.getWorkoutDesc());
        } else if (workoutView.getWorkoutType().equals("For Time")){
            holder.tvWorkoutName.setText(workoutView.getWorkoutName());
            holder.tvWorkoutType.setText(workoutView.getWorkoutType());
            holder.tvSetsItem.setText(workoutView.getWorkoutTime());
            holder.tvDescription.setText(workoutView.getWorkoutDesc());
        } else if (workoutView.getWorkoutType().equals("For Weight")){
            holder.tvWorkoutName.setText(workoutView.getWorkoutName());
            holder.tvWorkoutType.setText(workoutView.getWorkoutType());
            holder.tvSetsItem.setText(workoutView.getWorkoutWeight());
            holder.tvDescription.setText(workoutView.getWorkoutDesc());
        } else if (workoutView.getWorkoutType().equals("Other")){
            holder.tvWorkoutName.setText(workoutView.getWorkoutName());
            holder.tvWorkoutType.setText(workoutView.getWorkoutType());
            holder.tvDescription.setText(workoutView.getWorkoutDesc());
        }

    }

    holder.btnRemoveWorkout = (Button) convertView.findViewById(R.id.btnRemoveWorkout);
    holder.btnRemoveWorkout.setTag(position);
    holder.btnRemoveWorkout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (Integer) v.getTag();
            mCallback.onPressed(position);
        }
    });
    return convertView;
}

@Override
public WorkoutView getItem(final int position) {
    return mViews.get(position);
}

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

public interface Callback {
    void onPressed(int pos);
}

private static class ViewHolder {
    public TextView tvDescription;
    public TextView tvWorkoutType;
    public TextView tvWorkoutCategory;
    public TextView tvWorkoutWeight;
    public TextView tvSetsItem;
    public TextView tvRepsItem;
    public TextView tvWorkoutName;
    public Button btnRemoveWorkout;
}
}



回答4:


Hi try Removing the support library import android.support.v7.app.ActionBarActivity;

And extend Activity not ActionBarActivity. I have tried it and it work fine. The support library has some problems.



来源:https://stackoverflow.com/questions/29708159/add-a-button-to-a-listview-for-each-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!