Uses of Interfaces in android Development.
1 min readJan 9, 2017
It is a collection of constants, methods(abstract, static and default) and nested types.
- All the methods of the interface needs to be defined in the class.
- Interface is like a Class.
Class describes the behaviors of implements.
Difference From Class
- Can not instantiate an interface and can't contain instance fields.
- An interface has no constructors.
- All of the methods in an interface are abstract.
- All the fields that can appear in an interface must be declared both static and final.
- An interface can extend multiple interfaces.
The interface keyword is used to declare an interface.
public interface AdapterCallBackListener {
void onRowClick(String searchText);
}public interface OnFragmentInteractionListener {
void onFragmentInteraction();
}
A class uses the implements keyword to implement an interface.
public class CustomActivity extends AppCompatActivity
implements CustomAdapter.AdapterCallBackListener,
CustomFragment.OnFragmentInteractionListener{ void onRowClick(String searchText {
System.out.println("Today’s SearchText" + searchText);
} void onFragmentInteraction() {
System.out.println("On Fragment Interact");
}
}
Class uses Interface as function.
adapter.setCallBackListner(new CustomAdapter.AdapterCallBackListener() {
@Override
public void onRowClick(String searchText) {
Toast.makeText(CustomActivity.this,
searchText, Toast.LENGTH_SHORT).show();
}
});//setCallBackListner method declared in CustomAdapter.
Insert value in interfaces.
public class CustomAdapter {
private AdapterCallBackListener callBackListener; ................ ................
public void setCallBackListner(AdapterCallBackListener callBackListener) {
this.callBackListener = callBackListener;
} searchRow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
callBackListener.onRowClick(searchText);
}
});
public interface AdapterCallBackListener{
void onRowClick(String searchText);
}
}