简体   繁体   中英

Android Button ArrayList onClickListener doesn't work. Why?

I created an arraylist for the buttons and tablerows.

private ArrayList<Button> btDec = new ArrayList<Button>();
private ArrayList<TableRow> tr = new ArrayList<TableRow>();

Then I want to create a new button and tablerow and add tem to the tablelayout by using the following code in the onCreate() method.

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btDec.add(new Button(this));
            tr.add(new TableRow(this));

            int i = tr.size() - 1;
            btDec.get(i).setId(i);
            btDec.get(i).setText("-");
            tr.get(i).addView(btDec.get(i));
            lo.addView(tr.get(i), new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
        }
    });

All of this code works fine. But the following code (also in the onCreate() method) doesn't work. If I press the button, nothing happens and it doesn't print anything in the Logcat.

    for(int i = 0; i < tr.size(); i++)
    {
        btDec.get(i).setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Log.i("ButtonListener", "test");
            }
        });
    }

Please help me.

The problem is with this code

for(int i = 0; i < tr.size(); i++)
    {
        btDec.get(i).setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Log.i("ButtonListener", "test");
            }
        });
    }

You can't do it in onCreate() because tr list there is empty! You should add onClick listener when you create a button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM