To make thinks simple, I have made a custom calendar view (RelativeLayout). Events (linearLayouts) are placed inside it. When I click on the event I want to be able to do something, but I want this something to be done in my MainActivity. In other words I want to override the empty method in my custom view and handle it in my MainActivity.
eventView.setTag(event.getDatabaseId());
eventView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("test", "" + v.getTag());
onEventClick((int) v.getTag());
}
});
eventView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
onEventLongClick((int) v.getTag());
return false;
}
});
}
...
public void onEventClick(int eventId) {
}
public void onEventLongClick(int eventId) {
}
So in my MainActivity I instantiate my view:
cv = ((CalendarView)findViewById(R.id.calendar_view));
I want to do something like:
cv = ((CalendarView)findViewById(R.id.calendar_view)) {
@Override
public void onEventClick(int eventId) {
// here I will fetch the data and display a dialog
}
@Override
public void onEventLongClick(int eventId) {
// here I will fetch the data and display a dialog
}
};
I want to be able to use my calendar else where so this is why I don't want to tie the click functionality inside my custom view
I tried making my view abstract but got nowhere either.
EDIT: eventView's are in a viewpager
You should use Interface
on your custom view.
In its most common form, an interface is a group of related methods with empty bodies. You can find more detailed instructions here
So in your case I assume you have a RelativeLayout
as your custom view
public class MyCalendarLayout extends RelativeLayouts{
//Your constructor methods
public interface MyEventListener {
public void onEventClicked();
public void onEventLongClicked();
}
private MyEventListener myEventListener;
public void setListener(MyEventListener myEventListener) {
this.myEventListener= myEventListener;
}
}
Then on your Activity
you can use it like this
myCustomView.setListener(new MyEventListener() {
@Override
public void onEventClicked() {
// TODO Auto-generated method stub
}
@Override
public void onEventLongClicked() {
// TODO Auto-generated method stub
}
});
Or you can use
YourActivity extends Activity implements MyEventListener
and you can call
myCustomView.setListener(this);
on your activity and let the handle override methods to your activity.