-1

In this app I'm dynamically creating a counter object with a LinearLayout, TextView , and two Buttons, I want the onClickListener inside the class since that seems like the best solution.

The only thing I can think of is that I'm somehow getting the ID creation wrong. What are the best practices when dynamically creating things?

A screenshot of the app and all code is included.

public class Counter implements View.OnClickListener {

    private final int subButtonId = View.generateViewId();

...

    private void createSubButton() {

        subButton = new Button(context);
        subButton.setLayoutParams(new LinearLayout.LayoutParams(buttonWidth, LinearLayout.LayoutParams.MATCH_PARENT, 0.5f));
        subButton.setText("-");
        subButton.setTextSize(buttonTextSize);
        subButton.setId(subButtonId);
        subButton.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL);
        container.addView(subButton);

        sub = mainContainer.findViewById(subButtonId);
        sub.setOnClickListener(new MyOnClickListener() {
            @Override
            public void onClick(View v) {
                subCount();
                disp.setText(count.toString());
            }
        });
    }

}

class MyOnClickListener implements View.OnClickListener {


    public MyOnClickListener() {

    }

    @Override
    public void onClick(View v) {

    }
}

Counter Class: https://pastebin.com/YTHUbGFf

Main Class: https://pastebin.com/p3p2PPEU

Logcat: https://pastebin.com/0fYSKJyj

Image of App: https://i.stack.imgur.com/PyXwC.jpg

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bushfries
  • 11
  • 4

2 Answers2

0
  1. You don't need to find a view again. You can call subButton.setOnClickListener(...);
  2. I don't see any relation between container and mainContainer. You add view to your container, but is looking from mainContainer
Mike
  • 2,547
  • 3
  • 16
  • 30
0

You can directly setOnClickListener on subButton. I modified your createSubButton() method:

private void createSubButton() {

    subButton = new Button(context);
    subButton.setLayoutParams(new LinearLayout.LayoutParams(buttonWidth, LinearLayout.LayoutParams.MATCH_PARENT, 0.5f));
    subButton.setText("-");
    subButton.setTextSize(buttonTextSize);
    subButton.setId(subButtonId);
    subButton.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL);
    container.addView(subButton);

    subButton.setOnClickListener(new MyOnClickListener() {
        @Override
        public void onClick(View v) {
            //do something
        }
    });
}

}

Alvin Tom
  • 119
  • 4