I have a main activity with a lot of fragments. I have implemented the navigation drawer inside the main activity so that when I am viewing the fragments, I can open the navigation drawer as well. Inside the main_activity.xml
layout file (refer below), I have used <include layout="@layout/navigation_drawer"/>
to include the layout of the navigation drawer. Inside the navigation drawer, I have a lot of buttons and texts that redirect the user to different fragments.
Currently, I am handling all the onClick events of the navigation drawer inside the main activity. However, this makes my code inside the main activity very long and very hard to manage (in terms of readability and whether it is easy to edit). How to handle the onClick events in another class that specializes in handling the navigation drawer's event? What is the best way to achieve this?
main_activity.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer"
android:layout_height="match_parent"
android:layout_width="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<LinearLayout
android:id="@+id/drawerContent"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical">
<include layout="@layout/navigation_drawer"/>
</Linear Layout>
</android.support.v4.widget.DrawerLayout>
MainActivity class
public class MainActivity extends FragmentActivity implements View.OnClickListener, DrawerLayout.DrawerListener {
Button button1;
TextView text1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
button1 = (Button)findViewById(R.id.button1);
text1 = (TextView)findViewById(R.id.text1);
button1.setOnClickListener(this);
text1.setOnClickListener(this);
}
public void onClick(View v){
//I handle all onClick events of navigation drawer here.
//I want to move all of these to another class.
//If possible, I would like to move the onClick method and declaration of Button and TextView variables too.
}
}
Create a class which implement View.OnClickListener interface and pass newly created class object to widget setonclicklistner method public class MainActivity extends FragmentActivity implements View.OnClickListener, DrawerLayout.DrawerListener {
Button button1;
TextView text1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
button1 = (Button)findViewById(R.id.button1);
text1 = (TextView)findViewById(R.id.text1);
button1.setOnClickListener(new ClickHander());
}}
public class ClickHander implements View.OnClickListener
{
@Override
public void onClick(View v) {
}
}