Reputation: 1093
I am using dynamic menu with adapter class. When I want to go my main activity to another activity that time my navigation drawer is open. That's the reason when I back main activity the navigation drawer is open. I want to see, close the navigation drawer when I want to go main activity.
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
private ArrayList<MainMenu> arrayList = new ArrayList<>();
private DrawerLayout mDrawerLayout;
private TextView inTime;
private TextView lateEntryInMonth;
private Dashboard dashboard;
private SwipeRefreshLayout pullToRefresh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Gson gson = new Gson();
String json = sharedPrefs.getString("arraylist", "");
Type type = new TypeToken<ArrayList<MainMenu>>() {}.getType();
arrayList = gson.fromJson(json, type);
pullToRefresh = findViewById(R.id.pullToRefresh);
ImageView notification = findViewById(R.id.notification);
ImageView employeeImage = findViewById(R.id.iv_image);
TextView nameOfEmployee = findViewById(R.id.nameOfEmployee);
ExpandableListView ev_list = findViewById(R.id.ev_menu);
TextView tv_name = findViewById(R.id.tv_name);
RelativeLayout rl_menu = findViewById(R.id.rl_menu);
mDrawerLayout = findViewById(R.id.drawer_layout);
MenuAdapter obj_adapter = new MenuAdapter(MainActivity.this, arrayList);
lateEntryInMonth = findViewById(R.id.numberOfDayLateInMonth);
TextView monthLateEntry = findViewById(R.id.lateEntryMonth);
inTime = findViewById(R.id.today_time);
TextView hrNotice = findViewById(R.id.hr_notice);
hrNotice.setSelected(true);
hrNotice.setSingleLine(true);
dashboard = new Dashboard();
dashboard.setEMPLOYE_ID(PrefUtils.getUserID(getApplicationContext()));
ev_list.setAdapter(obj_adapter);
ev_list.setOnGroupClickListener((parent, v, groupPosition, id) -> {
int childCount = parent.getExpandableListAdapter().getChildrenCount(groupPosition);
if (childCount == 0) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
SharedPreferences preferences = getSharedPreferences("ActivityPREF", 0);
preferences.edit().remove("activity_executed").apply();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
setListViewHeight(parent, groupPosition);
}
return false;
});
setExpandableListViewHeightBasedOnChildren(ev_list);
tv_name.setText("Home");
rl_menu.setOnClickListener(view -> mDrawerLayout.openDrawer(Gravity.LEFT));
nameOfEmployee.setText(PrefUtils.getUserFullName(getApplicationContext()));
String photoId = PrefUtils.getUserPhotoId(getApplicationContext());
Glide.with(getApplicationContext())
.load(photoId)
.apply(RequestOptions.circleCropTransform())
.into(employeeImage);
monthLateEntry.setText("Late Entry In " + showMonthSummary());
notification.setOnClickListener(this);
new dashboardList().execute();
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
new dashboardList().execute();
pullToRefresh.setRefreshing(false);
}
});
}
@Override
protected void onResume() {
super.onResume();
//new dashboardList().execute();
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.notification:
Toast.makeText(MainActivity.this, "Under Development", Toast.LENGTH_SHORT).show();
break;
}
}
@SuppressLint("StaticFieldLeak")
private class dashboardList extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
String result;
result = HttpHandler.requestJsonInPOST(Constants.URL_EMPLOYEE_DASHBOARD_LIST_INFO, new Gson().toJson(dashboard));
return result;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//pullToRefresh.setRefreshing(true);
}
@Override
protected void onPostExecute(String result) {
//pullToRefresh.setRefreshing(false);
super.onPostExecute(result);
if (result != null) {
try {
String lateEntry =new JSONObject(result).getString("totalLate") + " Day";
lateEntryInMonth.setText(lateEntry);
inTime.setText(new JSONObject(result).getString("TodayLoginTime"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
}
private void setListViewHeight(ExpandableListView listView, int group) {
ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();
int totalHeight = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
View.MeasureSpec.EXACTLY);
for (int i = 0; i < listAdapter.getGroupCount(); i++) {
View groupItem = listAdapter.getGroupView(i, false, null, listView);
groupItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (((listView.isGroupExpanded(i)) && (i != group))
|| ((!listView.isGroupExpanded(i)) && (i == group))) {
for (int j = 0; j < listAdapter.getChildrenCount(i); j++) {
View listItem = listAdapter.getChildView(i, j, false, null,
listView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
int height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));
params.height = height;
listView.setLayoutParams(params);
listView.requestLayout();
}
public static void setExpandableListViewHeightBasedOnChildren(ExpandableListView expandableListView) {
MenuAdapter adapter = (MenuAdapter) expandableListView.getExpandableListAdapter();
if (adapter == null) {
return;
}
int totalHeight = expandableListView.getPaddingTop() + expandableListView.getPaddingBottom();
for (int i = 0; i < adapter.getGroupCount(); i++) {
View groupItem = adapter.getGroupView(i, false, null, expandableListView);
groupItem.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
totalHeight += groupItem.getMeasuredHeight();
if (expandableListView.isGroupExpanded(i)) {
for (int j = 0; j < adapter.getChildrenCount(i); j++) {
View listItem = adapter.getChildView(i, j, false, null, expandableListView);
listItem.setLayoutParams(new ViewGroup.LayoutParams(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED));
listItem.measure(View.MeasureSpec.makeMeasureSpec(0,
View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
totalHeight += listItem.getMeasuredHeight();
}
}
}
ViewGroup.LayoutParams params = expandableListView.getLayoutParams();
int height = totalHeight + expandableListView.getDividerHeight() * (adapter.getGroupCount() - 1);
if (height < 10)
height = 100;
params.height = height;
expandableListView.setLayoutParams(params);
expandableListView.requestLayout();
}
private String showMonthSummary() {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("MMMM", Locale.US);
return df.format(c);
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
This is adapter class. I also manage to go activity with this.
public class MenuAdapter extends BaseExpandableListAdapter {
Context context;
ArrayList<MainMenu> arraylist;
public MenuAdapter(Context context, ArrayList<MainMenu> arraylist) {
this.context = context;
this.arraylist = arraylist;
}
@Override
public int getGroupCount() {
return arraylist.size();
}
@Override
public int getChildrenCount(int i) {
return (arraylist.get(i).getSUB_MODULE_LIST() == null || arraylist.get(i).getSUB_MODULE_LIST().isEmpty()) ? 0 : arraylist.get(i).getSUB_MODULE_LIST().size();
}
@Override
public Object getGroup(int i) {
return arraylist.get(i);
}
@Override
public Object getChild(int i, int i1) {
return arraylist.get(i).getSUB_MODULE_LIST().get(i1);
}
@Override
public long getGroupId(int i) {
return i;
}
@Override
public long getChildId(int i, int i1) {
return i1;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.adapter_header, null);
}
TextView tv_header = view.findViewById(R.id.tv_header);
tv_header.setText(arraylist.get(i).getMLINK_NAME());
return view;
}
@Override
public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.adapter_childview, null);
}
TextView tv_state = view.findViewById(R.id.tv_child);
tv_state.setText(arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME());
tv_state.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Daily Work Report")) {
context.startActivity(new Intent(context, DailyWorkReportListActivity.class));
} else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Employee Contacts")) {
context.startActivity(new Intent(context, EmployeeContactsActivity.class));
} else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Add Ticket")) {
context.startActivity(new Intent(context, TicketActivity.class));
} else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("New Ticket")) {
context.startActivity(new Intent(context, TicketActivity.class));
} else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Leave Application")) {
context.startActivity(new Intent(context, LeaveStatusActivity.class));
} else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Movement ")) {
context.startActivity(new Intent(context, EmployeeMovementListActivity.class));
} else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Attendance")) {
context.startActivity(new Intent(context, AttendanceActivity.class));
//getActionBar().setDisplayHomeAsUpEnabled(false);
}else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Office Meal")) {
context.startActivity(new Intent(context, MealManagementUserActivity.class));
}
/*else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Call Information")) {
context.startActivity(new Intent(context, LastCallActivity.class));
} */else {
Toast.makeText(view.getContext(), "Under Development", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
@Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
Upvotes: 0
Views: 109
Reputation: 326
One way to achieve your desired behavior is to use an interface which method is called inside the MenuAdapter
.
Create an interface like the following:
public interface ActivityChangedListener {
public void onActivityChanged();
}
This interface should be implemented by an class that has an reference to the mDrawerLayout
that you want to close.
In this case we could make the Activity
implement the method like this:
public class MainActivity extends AppCompatActivity implements
ActivityChangedListener
public void onActivityChanged(){
mDrawerLayout.close();
}
Inside your MenuAdapter
you have to add the following:
public class MenuAdapter extends BaseExpandableListAdapter {
ActivityChangedListener activityChangedListener
public MenuAdapter(Context context, ArrayList<MainMenu> arraylist, ActivityChangedListener acl) {
this.context = context;
this.arraylist = arraylist;
// You could use a setter for this, but care because acl could be null if not set in the right order
this.activityChangedListener = acl;
}
// Now you have to call the listener inside the onClick method in every statement where you switch to a new activity
tv_state.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Daily Work Report")) {
activityChangedListener.onActivityChanged();
context.startActivity(new Intent(context, DailyWorkReportListActivity.class));
} else if (arraylist.get(i).getSUB_MODULE_LIST().get(i1).getMLINK_NAME().equals("Employee Contacts")) {
activityChangedListener.onActivityChanged();
context.startActivity(new Intent(context, EmployeeContactsActivity.class));
}
The only thing left is to edit the constructor call of MenuAdapter
and pass an instance of the ActivityChangedListener
, in this case it would be this
because our instance of the Activity
implements the interface:
MenuAdapter obj_adapter = new MenuAdapter(MainActivity.this, arrayList, this);
The use of an interface here is recommended to keep abstraction, expandability and transparency.
Upvotes: 1