Marek
Marek

Reputation: 1249

Extract some value in click listener from outer class

I have a custom class which has a unique interface

public class CalculatorDialog extends Dialog implements OnClickListener {
  TextView mView;
  CalculatorListener delegate = null;
  public CalculatorDialog (Context context, CalculatorListener delegate) {
    this.context = context;
    this.delegate = delegate;
  }
  public interface CalculatorListener extends OnClickListener {
    @Override void onClick(View v);
  }
  @Override void onCreate(Bundle bundle) {
    ...
    mView = (TextView) findViewById(...);
    findViewbyId(...Button...).setOnClickListener(delegate);
  }
  public String getViewText() {
    mView.getText().toString();
  }

When creating new object of CalculatorDialog I want to implement my own action for clicking Button, but I want to get some String from a visible text view.
So in my MainActivity I try to do this:

CalculatorDialog dialogBox = new CalculatorDialog(context, new CalculatorDialog.CalculatorListener() {}
    @Override
    public void onClick(View v) {
        String test = getViewText();
    }
});

But as you and I have thought it can't be accessed from there.
Code here is not 1:1 with what I have in my project, but I think it represenets my needs. Also I have wrote it directly on StackOverflow, so it may contain some code bugs.
How can I access this function?

Upvotes: 0

Views: 105

Answers (1)

Jesse Hoobergs
Jesse Hoobergs

Reputation: 86

You should change your CalculatorListener

 public class CalculatorDialog extends Dialog implements OnClickListener {
  TextView mView;
  CalculatorListener delegate = null;
  public CalculatorDialog (Context context, CalculatorListener delegate) {
    this.context = context;
    this.delegate = delegate;
  }
  public interface CalculatorListener{
    void onClick(View v, String text);
  }
  @Override void onCreate(Bundle bundle) {
    ...
    mView = (TextView) findViewById(...);
    findViewbyId(...Button...).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
             delegate.onClick(view, getViewText());
        });
  }
  public String getViewText() {
    mView.getText().toString();
  }

and

CalculatorDialog dialogBox = new CalculatorDialog(context, new CalculatorDialog.CalculatorListener() {}
    @Override
    public void onClick(View v, String text) {
        String test = text;
    }

Upvotes: 1

Related Questions