Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

android - set text in textview of a list item on click of button

I have created a list view as shown in this image.Link:

Image

Problem: I want that if the user clicks on the button + or - the textview which is currently showing 0 is incremented or decremented accordingly. But if I click first item's button the textview is updated in some other row. I don't know how to implement this.

Here's code:

public class HomePage extends Fragment {

    String[] listitems;
    int[] images = { R.drawable.cadburysilk, R.drawable.cadburys_dairymilk,
            R.drawable.perk, R.drawable.kitkat,
            R.drawable.nestlemunchchocolate, R.drawable.cadbury_bournville_bar,
            R.drawable.snickers };
    ListView list;
    DBAdapter dbadapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub

        View rootview = inflater.inflate(R.layout.activity_home_page,
                container, false);
        View view = View.inflate(getActivity(), R.layout.headerview, null);

        Resources res = getResources();
        listitems = res.getStringArray(R.array.items);
        list = (ListView) rootview.findViewById(R.id.itemslist);
        list.addHeaderView(view);
        AdapterClass adapterClass = new AdapterClass(this.getActivity(),
                listitems, images);
        list.setAdapter(adapterClass);
        return rootview;
    }

}

class AdapterClass extends ArrayAdapter<String> {
    Context context;
    int[] images;
    String[] names;
    Button add, sub;
    TextView number;
    Integer count=0;

    static class ViewHolder {
        public TextView textView;
        public ImageView imageView;

    }

    public AdapterClass(Context c, String[] items, int imgs[]) {
        // TODO Auto-generated constructor stub
        super(c, R.layout.rowlayout, R.id.quantity, items);
        this.context = c;
        this.images = imgs;
        this.names = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View row = convertView;
        // reuse views

        if (row == null) {

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.rowlayout, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.imageView = (ImageView) row.findViewById(R.id.img);
            viewHolder.textView = (TextView) row.findViewById(R.id.textView1);
            add = (Button) row.findViewById(R.id.button1);
            add.setTag(position);
            sub = (Button) row.findViewById(R.id.button2);
            sub.setTag(position);
            number = (TextView)row.findViewById(R.id.quantity);

            row.setTag(viewHolder);
        }
        ViewHolder holder = (ViewHolder) row.getTag();
        holder.imageView.setImageResource(images[position]);
        holder.textView.setText(names[position]);
        add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                count=count+1;
                number.setText(count.toString());
            }
        });

        sub.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                count=count-1;
                number.setText(count.toString());
            }
        });
        return row;
    }



}

Please help. Also i need help in how to show the items whose textview contains positive number in next activity or fragment.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wrote a short demo for my answer which you can see here.

Example:

When you're ready, you can then use your data source (not your adapter, not your listview) to find the products that have a quantity > 0.

    public List<Product> getBasket() {
        List<Product> basket = new ArrayList<>();
        for (Product product : productList) {
            if (product.quantity > 0) {
                basket.add(product);
            }
        }
        return basket;
    }

Your adapter has one job: to create/bind Views to data, it does not need to do more.


initial answer without demo:

If you update the item views directly, you won't be able to fetch all the items with a positive number later because these updated values are only stored in the views, and not in some data structure you can iterate over.

This is why you shouldn't update item views directly, but instead use a callback when the plus/minus button is clicked, modify the underlying dataset, and call adapter.notifyDatasetChanged() to update the ListView/RecyclerView again.

Pass a callback to your adapter:

public interface ItemInteraction {
    void onPlusButtonClick(long id);
    void onMinusButtonClick(long id);
}

which you can use by setting it as the callback for click listeners on the relevant views. The ID can be anything so long as it can uniquely identify the data item represented by a list view row.

final long id = item.getId();
plusButtonView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick() {
        callback.onPlusButtonClick(id);
    }
});

An example is given in this similar question where OP wanted to show or hide a star (indicating favourite) for a list of songs here.

Another explanation of how adapter-like views are designed to be used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...