动态setOnCLickListener

时间:2012-03-14 22:32:05

标签: android listener imagebutton

我正在使用包含来自SQLite数据库的行的表格布局,因此我添加了动态添加视图的行。现在,我在处理行版本的每一行中添加imageButton,并将其添加到SQLite数据库中。我想如果我选择正确的路径,那么如果有办法为每个生成的SetOnClickListener添加imageButton

1 个答案:

答案 0 :(得分:2)

我使用此代码为动态生成的按钮添加点击事件

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");



                });