0

I want to finish the Activity from my custom component. Question is how to get the reference of the Activity from my custom component? All I can get is Context in custom component. I tried to convert Context to Activity (code is below), and it seems ok. But I'm not sure about this. Perhaps there is a better way. So, please tell me if this code is good enough or has any problem or risk.

public class MyCustomComponent extends RelativeLayout {
private Activity activity;
public MyCustomComponent(Context context, AttributeSet attrs) {
    super(context);     
    Button btn = new Button(context);
    btn.setText("finish");
    addView(btn);

    activity = (Activity)context; // here I want to get the Acitivity reference
    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            MyCustomComponent.this.activity.finish();
        }
    });
}

}

hardPass
  • 19,033
  • 19
  • 40
  • 42

1 Answers1

0

How about passing the activity to your component?

public MyCustomComponent(Context context, Activity activity, AttributeSet attars)

edit You can add setActivity method to your class

public class MyCustomComponent extends RelativeLayout {
private Activity activity;

public void setActivity(Activity myActivity){
    activity = myActivity;
}

public MyCustomComponent(Context context, AttributeSet attrs) {
    super(context, attrs);
    Button btn = new Button(context);
    btn.setText("finish");
    addView(btn);
    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            activity.finish();
        }
    });
}

}

and in your main activity, add

    finishAction = (MyCustomComponent) findViewById(R.id.component);
    finishAction.setActivity(this);
Kendroid
  • 116
  • 4