Dynamic Buttons and OnClickListener

不问归期 提交于 2019-12-08 07:50:42

问题


Say I have buttons that are created dynamically:

for(int j = 0; j < spirits.length;

     j++){
                         Button imgBtn = new Button(v.getContext());
                         imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                         imgBtn.setMinimumWidth(100);
                         imgBtn.setMinimumHeight(100);
                         imgBtn.setId(j+1);
                         imgBtn.setTag(spirits[j]);
                         imgBtn.setText(spirits[j]);
                         imgBtn.setOnClickListener(new SpiritsClickListener());
                         cabinet_layout.addView(imgBtn);
                     }

I want to change the text of the button every time it's pressed (On - Off) How can I reference the buttons within the OnClickListener class?


回答1:


in your onClickListener, you have a function called onClick(View v){} where v is the View that was clicked. You may use v to get details about the button, including its ID. You can also take this view, and if you know it is a button, cast it to a button.

Button clicked = (Button)v;

You can then use it in your javacode just as you would normally use a button.




回答2:


Why don't you just call new OnClickListener() inside that loop like this

for(int j = 0; j < spirits.length;j++){
    Button imgBtn = new Button(v.getContext());
    imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    imgBtn.setMinimumWidth(100);
    imgBtn.setMinimumHeight(100);
    imgBtn.setId(j+1);
    imgBtn.setTag(spirits[j]);
    imgBtn.setText(spirits[j]);
    imgBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //do what you need to do here
        }
    });
    cabinet_layout.addView(imgBtn);
}



回答3:


Create an OnClickListener for dynamically created buttons as:

 // Create Listener  for Button
    private OnClickListener SpiritsClickListener = new OnClickListener()
    {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            Button btn = (Button) view;
           String btnText = btn.getText();

            if(btnText.equalsIgnoreCase("On")){
                 btn.setText("Off");
             }else{
                 btn.setText("On");
            }
        }
    };

add this Listener to dynamically created buttons as:

imgBtn.setOnClickListener(SpiritsClickListener);


来源:https://stackoverflow.com/questions/14088853/dynamic-buttons-and-onclicklistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!