Как закрыть и открыть навигационный ящик для динамического меню - PullRequest
0 голосов
/ 16 января 2019

Я использую динамическое меню с классом адаптера. Когда я хочу перейти с основного занятия на другое, в это время открывается окно навигации. Вот почему, когда я возвращаюсь к основному виду деятельности, ящик навигации открыт. Я хочу видеть, закрыть окно навигации, когда я хочу перейти к основной деятельности.

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();
}

Это класс адаптера. Мне также удается заняться этим.

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;
}

1 Ответ

0 голосов
/ 16 января 2019

Одним из способов достижения желаемого поведения является использование интерфейса , который вызывается внутри MenuAdapter.

Создайте интерфейс, подобный следующему:

public interface ActivityChangedListener {

   public void onActivityChanged();

}

Этот интерфейс должен быть реализован классом, имеющим ссылку на mDrawerLayout, который вы хотите закрыть. В этом случае мы могли бы заставить Activity реализовать метод следующим образом:

public class MainActivity extends AppCompatActivity implements 
ActivityChangedListener

public void onActivityChanged(){
  mDrawerLayout.close();
}

Внутри MenuAdapter вы должны добавить следующее:


    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));
    }

Осталось только отредактировать вызов конструктора MenuAdapter и передать экземпляр ActivityChangedListener, в этом случае это будет this, потому что наш экземпляр Activity реализует интерфейс:

MenuAdapter obj_adapter = new MenuAdapter(MainActivity.this, arrayList, this);

Рекомендуется использовать интерфейс для сохранения абстракции, расширяемости и прозрачности.

...