I'm trying to reduce the double effort of using the duplicate code. I searched on the google but didn't found about it that how we can reduce the duplication of code in android. May be this question could be stupid but I want the clarification.
1) The first thing I want to ask is that how we can reuse the same code in the multiple activity which are being using in overriden method as onBackPressed()
onOptionsItemSelected()
and so on. Here is the code which I'm currently writing in the onBackPressed()
method.
@Override
public void onBackPressed(){
if(this.mDrawerLayout.isDrawerOpen(GravityCompat.START)){
this.mDrawerLayout.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
For this approache I get the suggestion from this question to make the base activity then override this method after that extends other activities from that BaseActivity. But how I can pass the mDrawerLayout
field in the BaseActivity? how I can use findViewById()
on that base activity to access the xml widgets to access in the overriden method as currently using mDrawerLayout
layout.
Example in code.
public BaseActivity extends AppCompatActivity{
private DrawerLayout mDrawerLayout; // how to initialize it? where to call findViewById?
@Override
public void onBackPressed(){
if(this.mDrawerLayout.isDrawerOpen(GravityCompat.START)){
this.mDrawerLayout.closeDrawer(GravityCompat.START);
}else{
super.onBackPressed();
}
}
}
The same question for the onOptionsItemSelected()
mean menu item actions.
2) The second duplication I'm facing about hundred of time is startActivity()
I have to write Intent
then add the extra data if required than use that Intent. so about 2 to 3 lines I have to write again and again.
3) This thing is about the XML, I'm using the value 5dp
or 10dp
or 10sp
or other dimen
values in the XML file which are repeating a lot of time. So I want to ask is this approach will be Ok?
<dimen name="ten_dp">10dp</dimen>
android:layout_margin="@dimen/ten_dp"
Mean declare the dp
value then use that in the XML.
Edited:
4) This problem I have faced now. I'm using the same toolbar in all activities and after adding it in XML layout I have to write this code.
private void setupToolbar(){
setSupportActionBar(mainToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
}
}
But I have to re-write/copy the code in all activities. What is the solution of this problem?