首页 > 解决方案 > 如何在 ArrayList 中使用按钮

问题描述

我为“商品”视图制作了一个 ArrayAdapter 和 Array 列表,现在我想要它,这样每次我点击 + 按钮时,它都会增加我想要/点击的产品数量。我对 java 和 android Soz 很陌生。

So I wanna add this

int quantity = 1;

    /**
     * This method displays the given quantity value on the screen.
     */
    private void displayQuantity(int number) {
        TextView quantityTextView = findViewById(R.id.quantity_text_view);
        quantityTextView.setText(number);
    }


    /** this method is used to increase quantity*/
    public void add (View view) {
        quantity = quantity + 1;

        Log.v("merch","Added +1");

        displayQuantity(quantity);
    }

对此:

public class merchandise extends AppCompatActivity {

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

        ArrayList<Merch> merchArrayList = new ArrayList<Merch>();
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT1"));
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT2"));
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT3"));
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT4"));

        merchAdapter merchAdapter =  new merchAdapter(this,merchArrayList);
        GridView merchListView = (GridView) findViewById(R.id.merch_grid_view);
        merchListView.setAdapter(merchAdapter);
    }

我尝试过的事情:1)创建了一个新类并将其命名为“merch_buttons”,但是我收到一条错误消息,说“该方法应该在视图的父上下文中”,我不明白这一点。2)将它添加到 on create 但意识到您不能将方法添加到方法 3)在 on create 方法之后添加它但它给出了一个错误,说“java.lang.IllegalStateException:无法为android执行方法:点击“。

4) 尝试制作一个非常简单的新类和一个带有一个按钮和文本视图的 xml,但在 3).... 时仍然出错。

呜呜呜,怎么办。

标签: javaandroidarraysandroid-studiobutton

解决方案


在 onCreate() 中的 setContentView 之后初始化每个 UI Widget;举个例子,例如:

TextView quantityTextView = findViewById(R.id.quantity_text_view);

如果你想全局访问它,

public class merchandise extends AppCompatActivity {

    private TextView textView;

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

        textView = findViewById(R.id.quantity_text_view);

        ArrayList<Merch> merchArrayList = new ArrayList<Merch>();
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT1"));
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT2"));
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT3"));
        merchArrayList.add(new Merch(R.drawable.icon,"PRODUCT4"));

        merchAdapter merchAdapter =  new merchAdapter(this,merchArrayList);
        GridView merchListView = (GridView) findViewById(R.id.merch_grid_view);
        merchListView.setAdapter(merchAdapter);
    }

这些包括您尝试使用 onClick 的按钮。


推荐阅读