搜索过滤器在MainActivity中暗示不同的三个Fragment

时间:2019-06-19 09:29:33

标签: android android-fragments search

我的问题与WhatsApp搜索功能完全相关。 我有MainActivity:在该活动中,我有3个片段: 片段首页 片段办公室 片段其他

对于所有片段,我都有单个适配器类。 我将所有数据加载到全部3个片段中,但仅在UI中显示,这取决于类型home / office / other。

现在,我想暗示搜索过滤器。显然,我在MainActivity上做了。但是现在的问题是,如果用户从主页片段中搜索,它应该仅从主页片段中搜索。

请注意:所有三个片段的数据均不同。而且我在MainActivity中什么也不做。

代码:MainActivity:

import android.app.SearchManager;
import android.content.Context;
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.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
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.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.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.USERNAME;


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

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.list_view)
    RecyclerView listView;
    AdapterInterface listener;

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

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

    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();
                    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() {
        /*TODO:-> close search view on back button pressed*/
        if (!searchView.isIconified()) {
            searchView.setIconified(true);
        }

        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onClickFavorite(int isFavorite, int position) {
    }

    @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
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_OK) {
            switch (requestCode) {

            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.search:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.search)
                .getActionView();
        searchView.setSearchableInfo(searchManager
                .getSearchableInfo(getComponentName()));
        searchView.setMaxWidth(Integer.MAX_VALUE);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                return false;
            }
        });
        return true;
    }



    @Override
    public void onClickHamburger(int position) {

    }

    @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) {

    }
}

0 个答案:

没有答案