Make your android activity class code better!
Better code, the best app, and non-stop growth.
Maintaining the codebase is a big challenge nowadays based on the project size and contributors count. A more reliable codebase and architecture will help us in the time of enlargement, long term maintenance, and alteration.
Here are some tips which make your android app fine and pretty good seeming.
Activity/ Fragment View Holder.
The activity has the supreme responsibility for the user-interactions and presenting the view. Dumbing too much of code in that would always mess up. Having all codes like UI, permission handling, user-interactions, and data fetch initializing in the same class, We can separate the whole UI part.
public class MainActivity extends AppCompatActivity { private ConstraintLayout mainLayout;
private TextView inputView;
// and all your views will be a property of the class. @Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //here we will be initiating those properties by,
mainLayout = findViewById(R.id.main_layout); } private void addTheme() {
// if you have some ui rendering work in runtime. it will be taking place in the activity itself. }}
To get rid of All UI code in the activity. Create a class named {your_activity}ViewHolder. Now, the view holder of your activity is responsible for holding the reference of widgets. Not only the UI elements also doing UI related operations. To give an instance,
pubilc class MainActivityViewHolder { private ConstraintLayout mainLayout;
private TextView inputView; public MainActivityViewHolder(Activity activity) { // assign values to the properties;
} // all methods related to UI operations should take place in the activity view holder. void addTheme() { }
}public class MainActivity { private MainActivityViewHolder viewHolder; @Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewHolder = new MainActivityViewHolder(this); }
}
Now, your activity class will be freed from UI codes. Do the same for the fragment too. As well as create your complicated custom views as a separate XML with a separate class for that.