单击我的菜单过滤器(在MainActivity中排序)时,从MainActivity获取“片段确认”

时间:2019-06-25 11:27:33

标签: android

我在MainActivity中有一个菜单项是filter(sort),我希望如果用户单击A-z或z-a之类的过滤器菜单,在我的MainActivity的onclick中它也被单击了,但是我也想在片段中得到确认 [nhewuhfduehiuhuewhucuewcueucueuncnecineincincincinneincineinciniencineicnnecnnecneicniencnnecncncncnicncincincncnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnncnciciciicicicicicicicnnnncncicncn

代码:

MainActivity:

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Adapter.ViewPagerAdapter;
import com.tekitsolutions.remindme.Fragment.HomeFragment;
import com.tekitsolutions.remindme.Fragment.OfficeFragment;
import com.tekitsolutions.remindme.Fragment.OtherFragment;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Profile;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RemindMe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.tekitsolutions.remindme.Utils.CommonUtils.CREATE_PASSCODE_ACTIVITY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GET_PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IMAGE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_SEARCH;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.USERNAME;


public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, AdapterInterface, HamburgerMenuInterface, SearchListener, MenuItemListener {
    private static final String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.recycler_view)
    RecyclerView listView;

    private String phoneNum = null, getImage = null, getUsername = null;
    private int first = 0, position = 0;
    private ActionBar actionBar;
    private DatabaseAdapter dbAdapter;
    private ReminderListAdapter listAdapter;
    private List<Reminder> listItems = new ArrayList<>();
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private MenuItemListener searchListener;
    private DrawerLayout drawer;
    private SharedPreferences profilePreference;
    private TextView navUsername, navMobile;
    private ImageView navImage;
    private View headerView;
    private NavigationView navigationView;
    private SharedPreferences.Editor editor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        CREATE_PASSCODE_ACTIVITY = 0;
        setThemeAndLoadLocale(MainActivity.this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        ButterKnife.bind(this);
        setToolbar(toolbar, getString(R.string.app_name));
        profilePreference = getSharedPreferences(PROFILE, MODE_PRIVATE);
        getDataPhoneNumber();
        tabLayout = findViewById(R.id.tab_layout);
        viewPager = findViewById(R.id.view_pager);
        drawer = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.nav_view);
        headerView = navigationView.getHeaderView(0);
        navUsername = headerView.findViewById(R.id.profile_name);
        navMobile = headerView.findViewById(R.id.mobile_number);
        navImage = headerView.findViewById(R.id.profile_image);

        if (!phoneNum.isEmpty()) {
            first = 1;
            getProfileData();
        }

        Menu menu = navigationView.getMenu();
        MenuItem tools = menu.findItem(R.id.nav_general_setting);
        SpannableString s = new SpannableString(tools.getTitle());
        s.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s.length(), 0);
        tools.setTitle(s);

        Menu menu2 = navigationView.getMenu();
        MenuItem tools2 = menu2.findItem(R.id.nav_communicate);
        SpannableString s2 = new SpannableString(tools2.getTitle());
        s2.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s2.length(), 0);
        tools2.setTitle(s2);

        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        adapter.AddFragment(new HomeFragment(), getResources().getString(R.string.fragment_home));
        adapter.AddFragment(new OfficeFragment(), getResources().getString(R.string.fragment_office));
        adapter.AddFragment(new OtherFragment(), getResources().getString(R.string.fragment_other));



        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);


        listAdapter = new ReminderListAdapter(this, listItems, MainActivity.this, this, this);
        listView.setHasFixedSize(true);
        final LinearLayoutManager mLayoutManager;
        mLayoutManager = new LinearLayoutManager(this);
        listView.setLayoutManager(mLayoutManager);
        listView.setItemAnimator(new DefaultItemAnimator());
        try {
            listView.setAdapter(listAdapter);
        } catch (Exception exp) {
            exp.printStackTrace();
        }


        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, AddReminderActivity.class));
            }
        });


        dbAdapter = new DatabaseAdapter(this);
        HomeFragment homeFragment = new HomeFragment();
        homeFragment.setListener(this);

    }



    @Override
    public void onClickFavoriteById(int isFavorite, long id) {

    }

    private void setData() {
        if (getUsername != null && !getUsername.isEmpty()) {
            navUsername.setText(getUsername.trim());
        }
        if (phoneNum != null && !phoneNum.isEmpty()) {
            navMobile.setVisibility(View.VISIBLE);
            navMobile.setText(phoneNum);
        }
        if (getImage != null && !getImage.isEmpty()) {
            Bitmap bitmap = convertBase64ToBitMap(getImage);
            navImage.setImageBitmap(bitmap);
        } else {
            navImage.setImageResource(R.drawable.user_image);
        }
    }

    private void storeInSharedPreference() {
        editor = getSharedPreferences(PROFILE, MODE_PRIVATE).edit();
        editor.putString(USERNAME, getUsername);
        editor.putString(IMAGE, getImage);
        editor.apply();
    }

    private void getProfileData() {
        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
        Call<List<Profile>> profileDetails = apiInterface.getProfileDetails(phoneNum);

        profileDetails.enqueue(new Callback<List<Profile>>() {
            @Override
            public void onResponse(Call<List<Profile>> call, Response<List<Profile>> response) {
                int statusCode = response.code();

                if (statusCode == 200) {
                    List<Profile> responseList = response.body();

                    Profile profile = responseList.get(0);
                    showLog("username: " + profile.getProfileName());
                    getUsername = profile.getProfileName();
                    if (getUsername == null) {
                        showLog("Null");
                    } else {
                        showLog("Not null");
                    }

                    getImage = profile.getImage();
                    phoneNum = profile.getProfileNo();
                    setData();
                    storeInSharedPreference();
                }
            }

            @Override
            public void onFailure(Call<List<Profile>> call, Throwable t) {
                showLog("Failed: " + t.getMessage());
            }
        });

    }

    private void getDataFromSharedPref() {
        phoneNum = profilePreference.getString(PHONE_NUMBER, "");
        getUsername = profilePreference.getString(USERNAME, "");
        getImage = profilePreference.getString(IMAGE, "");
    }

    private void getDataPhoneNumber() {
        phoneNum = profilePreference.getString(PHONE_NUMBER, "");
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Intent intent = null;
        switch (item.getItemId()) {
            case R.id.nav_profile:
                intent = new Intent(this, ProfileActivity.class);
                intent.putExtra(GET_PROFILE, true);
                intent.putExtra(IMAGE, getImage);
                intent.putExtra(USERNAME, getUsername);
                startActivity(intent);
                break;
            case R.id.nav_favorite:
                intent = new Intent(MainActivity.this, AddFavoriteReminder.class);
                startActivity(intent);
                break;
            case R.id.nav_setting:
                intent = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(intent);
                break;

            case R.id.nav_passcode:
                intent = new Intent(this, PasscodeActivity.class);
                startActivity(intent);
                break;

            case R.id.nav_share:
                String link = "https://drive.google.com/drive/folders/1sDS_hGb5s5SjyDIK3me3oY8cS1Oo1I4F?usp=sharing";
                Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                SpannableString ss = new SpannableString("Android is a Software stack");

                String shareBodyText = link;
                sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here");
                sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
                startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));
                return true;

            case R.id.nav_help:
                intent = new Intent(MainActivity.this, HelpActivity.class);
                startActivity(intent);
                break;
            case R.id.nav_feedback:
                intent = new Intent(Intent.ACTION_SENDTO);
                intent.setType("message/rfc822");
                intent.setData(Uri.parse("mailto:"));
                intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"jimmytrivedi@outlook.com"});
                intent.putExtra(Intent.EXTRA_SUBJECT, "Remind Me Feedback");
                intent.putExtra(Intent.EXTRA_TEXT, "Developer Team,");
                try {
                    startActivity(Intent.createChooser(intent, "Send Email"));
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
                }

                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void onClickReminderList(int position) {

    }

    private Bitmap convertBase64ToBitMap(String profileImage) {
        try {
            byte[] encodeByte = Base64.decode(profileImage, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
            return bitmap;
        } catch (Exception e) {
            showLog("" + e.getMessage());
            return null;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        CREATE_PASSCODE_ACTIVITY = 0;
        if (RemindMe.isChanged()) {
            RemindMe.setChanged(false);
            recreate();
        }
        getDataFromSharedPref();
        setData();

    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.search:
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                startActivityForResult(intent, PICK_SEARCH);
                break;

            case R.id.filter:
                break;

            case R.id.ascending:
              position = 1;
                break;

            case R.id.descending:
              position = 2;
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_fragment_search, menu);
        getMenuInflater().inflate(R.menu.menu_filter, menu);
        return true;
    }


    @Override
    public void onClickHamburger(long id) {

    }

    @Override
    public void onClickListItem(int position) {

    }

    @Override
    public void setToolbar(Toolbar toolBar, String title) {
        super.setToolbar(toolBar, title);
    }

    private void showLog(String msg) {
        Log.d(TAG, msg);
    }

    @Override
    public void onSelectedProviderSearchItem(General general) {

    }

    @Override
    public void onSelectedParticularPaymentSearchItem(ParticularPayment particularPayment) {

    }

    @Override
    public void onSelectedReminderSearchItem(Reminder reminder) {

    }

    @Override
    public void unused(int position) {

    }

    @Override
    public void onFilterItem(int position) {
    }
}

界面

MenuItemListener

import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
public interface MenuItemListener {
    void onFilterItem(int position);
}

HomeFragment:

package com.tekitsolutions.remindme.Fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tekitsolutions.remindme.Activity.AddReminderActivity;
import com.tekitsolutions.remindme.Activity.MainActivity;
import com.tekitsolutions.remindme.Activity.ReminderDetailActivity;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Receiver.AlarmReceiver;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RecyclerViewClickListener;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_FAVORITE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_TYPE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.HOME;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IS_EDIT;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_HOME;

public class HomeFragment extends Fragment implements AdapterInterface, HamburgerMenuInterface, Callback<String>, SearchListener, MenuItemListener {
    private static final String TAG = HomeFragment.class.getSimpleName();
    public MainActivity activity;
    public Context context;
    View view;
    private DatabaseAdapter dbAdapter;
    private List<Reminder> listItems = new ArrayList<>();
    private ReminderListAdapter listAdapter;
    private MenuItemListener menuItemListener;
    private RecyclerView listView;
    private TextView tvNoData;
    private AdapterInterface listener;
    private HamburgerMenuInterface menuInterface;
    private AlertDialog.Builder builder;
    private Reminder reminder;
    private long reminderId = 0;
    private int getFavorite = 0;

    public HomeFragment() {
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragment, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView = view.findViewById(R.id.recycler_view);
        tvNoData = view.findViewById(R.id.tv_no_data);
        dbAdapter = new DatabaseAdapter(getContext());
        listAdapter = new ReminderListAdapter(getActivity(), listItems, HomeFragment.this, this, this);
        listView.setHasFixedSize(false);
        final LinearLayoutManager mLayoutManager;
        mLayoutManager = new LinearLayoutManager(getActivity());
        listView.setLayoutManager(mLayoutManager);
        listView.setItemAnimator(new DefaultItemAnimator());
        try {
            listView.setAdapter(listAdapter);
        } catch (Exception exp) {
            exp.printStackTrace();
        }

        listView.addOnItemTouchListener(new RecyclerViewClickListener.RecyclerTouchListener(getContext(),
                listView, new RecyclerViewClickListener.ClickListener() {
            @Override
            public void onClick(View view, int position) {

            }

            @Override
            public void onLongClick(View view, int position) {
            }
        }

        ));
        loadAllReminders();
    }

    @Override
    public void onStart() {
        super.onStart();
        loadAllReminders();
    }

    private void loadAllReminders() {
        listItems.clear();
        List<Reminder> list = dbAdapter.getReminderById(REMINDER_TYPE_ID, HOME);
        if (list.size() > 0) {
            tvNoData.setVisibility(View.GONE);
            listItems.addAll(list);

            listAdapter.notifyDataSetChanged();
        } else {
            tvNoData.setVisibility(View.VISIBLE);
        }
    }



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.menuItemListener = (MenuItemListener) getActivity();
    }


    private void showLog(String msg) {
        Log.d(TAG, msg);
    }

    @Override
    public void onFilterItem(int position) {
        showLog("test: " + position);
    }

    public void setListener(MenuItemListener listener) {
        this.menuItemListener = listener;
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用EventBus或Interface来执行此操作。您可以为EventBus执行以下步骤。

实施EventBus

implementation 'org.greenrobot:eventbus:3.1.1'

EventBustDataEvents.class

public class EventBusDataEvents{
    public static class isClick {
        boolean isClick;

        public isClick(boolean isClick) {
            this.isClick = isClick;
        }

        public boolean getIsClick() {
            return isClick;
        }

        public void setIsClick(boolean isClick) {
            this.isClick = isClick;
        }
    }
}

MainActivity.class

EventBus.getDefault().postSticky(new EventBusDataEvents.isClick(true));

Fragment.class

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void isClick(EventBusDataEvents.isClick click) {
        if (click.isClick()) {

        }
    }

@Override
public void onStart() {
    super.onStart();
    try {
        EventBus.getDefault().register(this);
    } catch (Exception e) {
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    try {
        EventBus.getDefault().unregister(this);
    } catch (Exception e) {
    }
}

或界面

IMainActivity.class //接口类

public interface IMainActivity {
void onClick();}

MainActivity.class

private IMainActivity listener; //This will be described above as a field.

     public void setOnEventListener(IMainActivity listener) {
            IMainActivity = listener;
        }

//buttonClickEvent
listener.OnClick();

Fragment.class

//onCreateView
    setOnEventListener(new IMainActivity() {
            @Override
            public void onClick() {

            }
        });