dynamic setOnCLickListener

2019-07-26 05:00发布

I'm using a table layout with rows that comes from an SQLite database, so I add the rows dynamically adding views to a row. Now, I added and imageButton in each row that handle the row edition and other that add it to the SQLite database. I would like if I go for the right path, so if there is a way to add a SetOnClickListener to each generated imageButton?

1条回答
【Aperson】
2楼-- · 2019-07-26 05:09

I used this code for adding click events for dynamically generated button

for (int position=0; position < parseInt; position++)
        {
            TableRow tableRow= new TableRow(this);

            tableRow.setBackgroundColor(006400);
//          ArrayList<Object> row = data.get(position);


            TextView idText = new TextView(this);
            idText.setText(Integer.toString(position + 1));
            idText.setGravity(Gravity.CENTER);
            idText.setTextColor(Color.BLACK);
            idText.setWidth(10);
            idText.setHeight(30);
            idText.setBackgroundResource(R.drawable.textbg);
//          idText.setPadding(0, 0, 1,0);

             tableRow.addView(idText);



            //THE CLICK EVENT OF BUTTON
            Button  textOne = new Button(this);
            textOne.setText("CLUB");
            textOne.setBackgroundResource(R.drawable.textbg);
            textOne.setGravity(Gravity.CENTER);
            textOne.setTextColor(Color.BLACK);//left top right bottom
//          textOne.setPadding(2, 1, 1,0);
//          textOne.setB;

            textOne.setWidth(10);
            textOne.setHeight(30);

            textOne.setId(1+position);
            tableRow.addView(textOne);


//          textOne.setOnClickListener(this);

             textOne.setOnClickListener(new OnClickListener() {
                public void onClick(View arg0) {
                  // do something when the button is clicked

                    final Button button = (Button) arg0;



 System.out.println("button is clicked");



                });
查看更多
登录 后发表回答