简体   繁体   中英

OnClickListener for Dynamically created buttons

I'm new to android Development and I hope you can help me.I created Buttons Dynamically ( Based on the contents of my Database). I also made onclicklistener for those buttons. The problem now is, If I click the buttons, Nothing happens. There is also no error shown in logcat. Why do you think this happened? Any response will be appreciated.

Here is my code on creating buttons:

final LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        cursorCol = scoresDataBaseAdapter.queueCrit(mRowId);
        for(cursorCol.move(0); cursorCol.moveToNext(); cursorCol.isAfterLast()){
            int Id = Integer.parseInt(cursorCol.getString(cursorCol.getColumnIndex("_id")));
            Log.i("_id","_id : "+Id);
                String  CriteriaButton = cursorCol.getString(cursorCol.getColumnIndex("Criteria"));
               Log.i("CriteriaButton","CriteriaButton : " + CriteriaButton);


                 Button btn = new Button(this);
                    btn.setText("  " + CriteriaButton + "  "); 
                    btn.setId(Id);
                    btn.setTextColor(Color.parseColor("#ffffff"));
                    btn.setTextSize(12);
                    btn.setPadding(10, 10, 10, 10);
                    btnlayout.addView(btn,params); 

                    btn.setOnClickListener(getOnClickDoSomething(btn));}

Now after my OnCreate, I have the following method to set the onclicklistener

View.OnClickListener getOnClickDoSomething(final Button button)  {
            return new View.OnClickListener() {
                public void onClick(View v) {

                    String criteria = button.getText().toString();
                    if ("Exams".equals(criteria)){
                        Toast.makeText(getApplicationContext(),"Exams Selected",2).show();  } 

                    else if ("Quizzes".equals(criteria)){
                        Toast.makeText(getApplicationContext(),"Quizzes Selected",2).show();  } 

                }
            };
        }

Change

String criteria = button.getText().toString();

to

String criteria = button.getText().toString().trim();

Inside onClick method use View parameter of onClick method to get Text from pressed button as:

public void onClick(View v) {
    Button button = (Button)v;
    String selectedText = button.getText().toString();
    ....your code here
}

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