BASIC INTERFACE AS A COMMUNICATOR
How to create an interface:
public interface ItemClickListener {
void onItemClick(String message);
}
An Interface has two User class.
Sender:
who send data through the interface;
How to use:
1. First of all declare interface as member variable in the sender class.
private ItemClickListener mItemClickListener;
2. Create a setter for this member variable. So that receiver can access the same listener
public void setItemClickListener(ItemClickListener itemClickListener){
this.mItemClickListener=itemClickListener;
}
3. Now for sending data:
String msg="hello";
mItemClickListener.onItemClick(msg);
Reciever
How to use:
We can use an interface as a receiver in several way.
Way 1 implementing:
class reciever implements ItemClickListener{
//that will force you to override the interface methods
}
Create an object of Interface:
private sender mSender;
on any method like main or onCreate initialize the object
void anyMethod(){
mSender=new sender();
}
now use the setter from the sender to set the interface;
void anyMethod(){
mSender=new sender();
mSender.setItemClickListener(this);
}
After implementing:
class reciever implements ItemClickListener{
@Override
public void onItemClick(String message) {
}
}
Now we can use the variable :
class reciever implements ItemClickListener{
@Override
public void onItemClick(String message) {
Toast.makeText(mContext, ""+ message, Toast.LENGTH_SHORT).show();
}
}
output:
hello
way 2 :
Without implementing interface on class.
1. First we need to create an object of sender class
private sender mSender;
void anyMethod(){
mSender=new sender();
}
2. Now use object of using setter.
void anyMethod(){
mSender=new sender();
mSender.setItemClickListener(new ItemClickListener() {
@Override
public void onItemClick(String message) {
Toast.makeText(mContext, ""+message, Toast.LENGTH_SHORT).show();
}
});
}