How to move Recycleview item to Fragment of navigation Drawer? - android

I want to start intent from ViewHolder class to the Fragment of Navigation Drawer Fragment class. Please see the code below.
public class LinearViewHolder extends RecyclerView.ViewHolder {
public TextView countryName;
public ImageView countryPhoto;
public Context context;
public LinearViewHolder(View v) {
super(v);
context = itemView.getContext();
countryName = (TextView) itemView.findViewById(R.id.country_name);
countryPhoto = (ImageView) itemView.findViewById(R.id.country_photo);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos == 0) {
//here we go to ActivityFragment class???
} else if (pos == 1) {
//here we go to ActivityFragment class???
} else if (pos == 2) {
//here we go to ActivityFragment class???
} else if (pos == 3) {
} else if (pos == 4) {
} else if (pos == 5) {
}
}
});
}
}
And the FragmentActivity.class code is this below!
public class ActivityFragment extends Fragment {
private List<ActivitySetData> history;
RecyclerView recList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.actvity_toolbar, container, false);
Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar_two);
setSupportActionBar(toolbar);
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) v.findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) v.findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
try {
Glide.with(this).load(R.color.light_blue).into((ImageView) v.findViewById(R.id.backdrop));
} catch (Exception e) {
e.printStackTrace();
}
recList = (RecyclerView) v.findViewById(R.id.recycler_view);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
initializeData();
initializeAdapter();
return v;
}
private void initializeData() {
history = new ArrayList<>();
history.add(new ActivitySetData(R.color.light_blue, "Getting knowing the Activity", getString(R.string.activity_first)));
history.add(new ActivitySetData(R.color.light_blues1, "Navigation Through Activities", getString(R.string.activity_second)));
history.add(new ActivitySetData(R.color.light_blues2, "Tasks", getString(R.string.activity_third)));
history.add(new ActivitySetData(R.color.light_blues3, "The Talkback Stack", getString(R.string.activity_four)));
history.add(new ActivitySetData(R.color.light_blues4, "Activity Life Cycle", getString(R.string.activity_five)));
history.add(new ActivitySetData(R.color.light_blues6, "Activity Life Cycle Methods", getString(R.string.activity_six)));
}
private void initializeAdapter() {
ActivityAdapter adapter = new ActivityAdapter(history);
recList.setAdapter(adapter);
}
private void setSupportActionBar(Toolbar toolbar) {
}
}
And the code of my Parent MainActivity.class is below
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Defining Variables
private NavigationView navigationView;
private DrawerLayout drawerLayout;
String showFragmentCheck;
private TextView tool;
FragmentManager mFragmentManager;
LinearLayout linearLayoutSelectLocation;
private TextView textViewCancel;
private TextView textViewLike;
private TextView textViewShare;
private ImageView ic_short;
private FloatingActionButton fab;
private static final String SHOWCASE_ID = "sequence example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
register_view();
presentShowcaseSequence(); // one second delay
textViewLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=app.mytutoandroid"));
startActivity(browserIntent);
}
});
textViewShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=app.mytutoandroid");
startActivity(intent);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
textViewCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayoutSelectLocation.setVisibility(View.INVISIBLE);
}
});
ic_short.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UiShortcuts.class);
// intent.putExtra("lastFragment","News");
startActivity(intent);
finish();
}
});
mFragmentManager = getSupportFragmentManager();
showFragmentCheck = getIntent().getStringExtra("checkFragment");
if (showFragmentCheck == null) {
showChildFragment("Getting Started");
} else {
showChildFragment(showFragmentCheck);
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawerLayout.closeDrawers();
showChildFragment(menuItem.getTitle().toString());
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name,
R.string.app_name);
drawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
public void register_view() {
tool = (TextView) findViewById(R.id.toolbar_title);
tool.setOnClickListener(this);
textViewLike = (TextView) findViewById(R.id.textViewLike);
textViewShare = (TextView) findViewById(R.id.textViewShare);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
textViewCancel = (TextView) findViewById(R.id.textViewCancel);
linearLayoutSelectLocation = (LinearLayout) findViewById(R.id.linearLayoutSelectLocation);
ic_short = (ImageView) findViewById(R.id.choose_short);
ic_short.setOnClickListener(this);
}
public void showChildFragment(String fragmentTitle) {
if (fragmentTitle.equals("Activity")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Activity");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ActivityFragment()).commit();
} else if (fragmentTitle.equals("Getting Started")) { // on 2nd item in the menu, do somethin
tool.setText("Android Development");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new MainFragment()).commit();
} else if (fragmentTitle.equals("Services")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Services");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ServicesFragment()).commit();
} else if (fragmentTitle.equals("Content Provider")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Content Provider");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ContentFragment()).commit();
} else if (fragmentTitle.equals("BroadCast Receiver")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to BroadCast Receiver");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new BroadCastFragment()).commit();
} else if (fragmentTitle.equals("Networking")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Networking");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new NetworkingFragment()).commit();
} else if (fragmentTitle.equals("Android Manifest")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Manifests");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ManiFragment()).commit();
} else if (fragmentTitle.equals("References")) { // on 2nd item in the menu, do somethin
tool.setText("References");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new References()).commit();
} else {
showChildFragment("Getting Started");
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.choose_short || v.getId() == R.id.toolbar_title) {
presentShowcaseSequence();
}
}
private void presentShowcaseSequence() {
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(500); // half second between each showcase view
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(this, SHOWCASE_ID);
sequence.setOnItemShownListener(new MaterialShowcaseSequence.OnSequenceItemShownListener() {
#Override
public void onShow(MaterialShowcaseView itemView, int position) {
Toast.makeText(itemView.getContext(), "Item #" + position, Toast.LENGTH_SHORT).show();
}
});
sequence.setConfig(config);
sequence.addSequenceItem(ic_short, "Shortcut for Android topics\nFind the Android Content with details.", "GOT IT");
sequence.start();
}
}

In Adapter
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos == 0) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("checkFragment", "ActivityFragment");
context.startActivity(intent);
} else if (pos == 1) {
//same as above
} else if (pos == 2) {
///same as above
} else if (pos == 3) {
} else if (pos == 4) {
} else if (pos == 5) {
}
}
});
In MainActivity
mFragmentManager = getSupportFragmentManager();
showFragmentCheck = getIntent().getStringExtra("checkFragment");
if (showFragmentCheck == null) {
showChildFragment("Getting Started");
} else {
if (showFragmentCheck.equalsIgnoreCase("ActivityFragment")) {
showChildFragment("Activity");
}else
{
showChildFragment(showFragmentCheck);
}
}

try with this way or try with this link Click Here to more
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Dependency:-
compile 'com.android.support:recyclerview-v7:21.0.0-rc1'
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
}
public class ContactInfo {
protected String name;
protected String surname;
protected String email;
protected static final String NAME_PREFIX = "Name_";
protected static final String SURNAME_PREFIX = "Surname_";
protected static final String EMAIL_PREFIX = "email_";
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vSurname;
protected TextView vEmail;
protected TextView vTitle;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vSurname = (TextView) v.findViewById(R.id.txtSurname);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vTitle = (TextView) v.findViewById(R.id.title);
}
}
public class ContactAdapter extends
RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vSurname.setText(ci.surname);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vTitle.setText(ci.name + " " + ci.surname);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
...
}
}

Related

How to display only one fragment tab in Android

I have different fragments in my MainActivity. In each fragment I implemented some features.
Now I am trying to implemented tabs for one fragments, what I'm looking for is about hide tab layout in remaining fragments.
activity.xml:
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.genworks.oppm.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/activity_search_view_check"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="#layout/toolbar"/>
<include layout="#layout/search_toolbar"
android:visibility="gone"/>
</RelativeLayout>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabIndicatorColor="#color/White"
app:tabTextColor="#color/White"
android:background="#drawable/button_background"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:tabGravity="fill"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
Fragment fragment;
int CAMERA_PIC_REQUEST=20;
Menu search_menu;
MenuItem item_search;
ExpandableListView expListView;
TabLayout tabLayout;
private ProgressDialog progressDialog = null;
TextView user,firstname,lastname,mobile,role,report_to;
String user_name;
ImageView profile;
private ArrayList<Records> records;
private ArrayList<Records> recordsList=new ArrayList<>();
ViewPager viewPager;
TextView mTitle;
private RecyclerView recyclerView;
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_GALLERY_PHOTO = 2;
File mPhotoFile;
FileCompressor mCompressor;
private RecyclerView.Adapter mAdapter;
String sessionId,username,first_name,last_name,mobile_no,role_id,reportto;
MenuItem refreshMenuItem;
ExpandableListView expandableList;
ExpandableListAdapterMenu mMenuAdapter;
List <ExpandedMenuModel> listDataHeader;
private final Handler handler = new Handler ( );
HashMap <ExpandedMenuModel, List <String>> listDataChild;
private RecyclerView.LayoutManager layoutManager;
private boolean ismenutoggle;
private Toolbar searchtollbar,toolbar;
boolean needLogin = false;
LinearLayout dashboard,taskmenu,account,contact,opportunity,logout,documents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionId = getIntent().getStringExtra("sessionId");
username = getIntent().getStringExtra("username");
PreferenceUtils.getUsername(this);
PreferenceUtils.getPassword(this);
first_name = getIntent().getStringExtra("firstname");
last_name = getIntent().getStringExtra("lastname");
mobile_no = getIntent().getStringExtra("mobile");
role_id = getIntent().getStringExtra("role");
reportto = getIntent().getStringExtra("reportto");
dashboard=findViewById(R.id.dashboard);
taskmenu=findViewById(R.id.taskmenu);
contact=findViewById(R.id.contactmenu);
opportunity=findViewById(R.id.opportunitymenu);
account=findViewById(R.id.accountmenu);
logout=findViewById(R.id.logout);
// user = (TextView) findViewById(R.id.username);
profile=findViewById(R.id.profile);
mCompressor = new FileCompressor(this);
firstname = (TextView) findViewById(R.id.firstname);
lastname = (TextView) findViewById(R.id.lastname);
mobile=findViewById(R.id.mobile);
role=findViewById(R.id.role);
report_to=findViewById(R.id.report_to);
firstname.setText(first_name);
lastname.setText(last_name);
mobile.setText(mobile_no);
role.setText(role_id);
report_to.setText(reportto);
// user.setText(username);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("DASHBOARD");
final ActionBar ab = getSupportActionBar();
ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ab.setCustomView(R.layout.toolbar_spinner);
if (ab != null) {
ab.setDisplayShowTitleEnabled(false);
mTitle = (TextView) findViewById(R.id.toolbar_title);
mTitle.setText("DASHBOARD");
mTitle.setGravity(Gravity.CENTER_HORIZONTAL);
// Typeface typeface = Typeface.createFromAsset(getApplicationContext ().getAssets (), "fonts/astype - Secca Light.otf");
// mTitle.setTypeface (typeface);
}
ab.setHomeAsUpIndicator(R.drawable.menu);
ab.setDisplayHomeAsUpEnabled(true);
//ab.setTitle ("HOME");
setSearchtollbar();
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
fragment = new DashboardFragement();
loadFragment(fragment);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
if (navigationView != null) {
setupDrawerContent (navigationView);
}
// TextView dashboard=findViewById(R.id.menu_dashboard);
dashboard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Dashboard");
fragment = new DashboardFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView task=findViewById(R.id.menu_task);
taskmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Task List");
fragment = new TaskFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Account List");
fragment = new AccountFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Contact List");
fragment = new ContactFragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView opportunity=findViewById(R.id.menu_opportunity);
opportunity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Opportunity List");
fragment = new SalesStageFragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView logout=findViewById(R.id.menu_logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
drawerLayout.closeDrawer(GravityCompat.START);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
initBottomNavigationItems();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TaskFragement(), "All");
adapter.addFragment(new AccountFragement(), "Incomplete");
adapter.addFragment(new ContactFragment(), "Scheduled");
adapter.addFragment(new ContactFragment(), "Today");
adapter.addFragment(new ContactFragment(), "Weekwise");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Gallery",
"Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
MainActivity.this.requestStoragePermission(true);
} else if (items[item].equals("Choose from Gallery")) {
MainActivity.this.requestStoragePermission(false);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void initBottomNavigationItems() {
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.account:
mTitle.setText("ACCOUNT LIST");
fragment = new AccountFragement();
loadFragment(fragment);
return true;
case R.id.task:
mTitle.setText("TASK LIST");
fragment = new TaskFragement();
loadFragment(fragment);
return true;
case R.id.contact:
mTitle.setText("CONTACT LIST");
fragment = new ContactFragment();
loadFragment(fragment);
return true;
case R.id.opportunity:
mTitle.setText("OPPORTUNITY LIST");
fragment = new SalesStageFragment();
loadFragment(fragment);
return true;
}
return false;
}
});
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
menu.findItem(R.id.search).setVisible(false);
return true;
}
private void setupDrawerContent(NavigationView navigationView) {
//revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if(menuItem.isChecked ()){
drawerLayout.openDrawer (GravityCompat.START);}
else {
drawerLayout.closeDrawer (GravityCompat.START);
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(ismenutoggle==true) {
drawerLayout.openDrawer (GravityCompat.START);
ismenutoggle=false;
}
else{
drawerLayout.closeDrawer (GravityCompat.START);
ismenutoggle=true;
}
return true;
}
return super.onOptionsItemSelected(item);
}
private AdapterView.OnItemClickListener mDrawerItemClickedListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
}
};
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
finish();
}
}
private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener () {
#Override
public void onDrawerStateChanged(int status) {
}
#Override
public void onDrawerSlide(View view, float slideArg) {
}
#Override
public void onDrawerOpened(View view) {
drawerLayout.openDrawer (view);
}
#Override
public void onDrawerClosed(View view) {
drawerLayout.closeDrawer (view);
}
};
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close_black_24dp);
// closeButton.setImageResource(ContextCompat.getDrawable(getApplication(), R.drawable.ic_close_black_24dp));
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
Log.i("query", "" + query);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
public void setActionBarTitle(String title) {
mTitle.setText(title);
}
}
I think you are asking if we can create two tabs and when the user presses any of the tab, same fragment should appear instead of multiple fragments. If that is your question, may be i can help.
You will have to create one class that extends FragmentStateAdapter , then you should create a single class that extends Fragment instead of having multiple classes and a layout.
Create ClassFragmentPagerAdapter like this:
public class ClassFragmentPagerAdapter extends FragmentStateAdapter {
public ClassFragmentPagerAdapter (#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
if (position == 0) {
return new ClassFragment ();
}
return new ClassFragment ();
}
#Override
public int getItemCount() {
return 2;
}
Then after that create the other ClassFragment that extends Fragment:
public class ClassFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.layout_name, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
//do stuff here
}
Hope it helps! Happy coding:)

Update RecyclerView from menu

I have a MainActivity with two fragments. The second fragment has RecyclerView. There is TextView ( lesson name) and ImageView(show lesson status, if it is done or not) in RecyclerView . When you click TextView, it calls another Activity with lesson. After you make the lesson you will go back to MainActivity. After that lessons ImageView will be changed from nothing to resourse 'ic_lessondone'. Also there is a menu in MainActivity. Menu have item 'Reset lessons'. When you press 'Reset lessons' all ImageViews wont show any images. So there are two problems. 1) if I do, for example , only 6th lesson. I will have image 'lessondone'. When i press 'Reset lessons' image will disappear. But when i go back to menu again and press 'Reset lessons', Image will appear again and rise to previous lesson ( 5th). 2) If i switch off display, image will also appear to previous lessons till to 0th.
Its seems i have a problem with onResume.
Help me please.
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null)
{
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
{
setupViewPager(viewPager);
}
// Круглая кнопка
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Картинки для табов
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_lessons);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
switch (AppCompatDelegate.getDefaultNightMode())
{
case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
menu.findItem(R.id.menu_night_mode_system).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_AUTO:
menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
menu.findItem(R.id.menu_night_mode_night).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
menu.findItem(R.id.menu_night_mode_day).setChecked(true);
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_system:
setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
break;
}
return super.onOptionsItemSelected(item);
}
private void setNightMode(#AppCompatDelegate.NightMode int nightMode)
{
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11)
{
recreate();
}
}
private void setupViewPager(ViewPager viewPager)
{
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new Fragment(), "");
adapter.addFragment(new LessonsListFragment(), "");
viewPager.setAdapter(adapter);
}
// Главное меню
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
if (menuItem.getTitle().equals("Reset lessons"))
{
// Обнуляем файл с рузультатами уроков
LessonsListFragment.sLessonsPref.edit().clear().commit();
// Перерисовываем весь писок уроков
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm)
{
super(fm);
}
public void addFragment(Fragment fragment, String title)
{
mFragments.add(fragment);
mFragmentTitles.add(title);
}
// Получаем конкретный фрагмент
#Override
public Fragment getItem(int position)
{
return mFragments.get(position);
}
// Количество фрагментов для viewpager (2)
#Override
public int getCount()
{
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitles.get(position);
}
}
}
Fragment
public class LessonsListFragment extends Fragment
{
// Уроки
// static private Map<String,?> mLessonsKeys ;
static SharedPreferences sLessonsPref;
static RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
loadSharedPreferenses();
rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
// Загружаем список пройденных уроков
public void loadSharedPreferenses()
{
sLessonsPref = this.getActivity().getSharedPreferences("LessonsResults", Context.MODE_PRIVATE);
}
// Количество строк в листе
private void setupRecyclerView(RecyclerView recyclerView)
{
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, Cheeses.sCheeseStrings.length)));
}
// Задаем Строки
private List<String> getRandomSublist(String[] array, int amount)
{
ArrayList<String> list = new ArrayList<>(amount);
//Random random = new Random();
while (list.size() < amount)
{
list.add(array[list.size()]);
}
return list;
}
//Отработка перерисования окна, при возврате к ней
#Override
public void onResume()
{
super.onResume();
//loadSharedPreferenses();
//Toast.makeText(null, "Refreshed", Toast.LENGTH_SHORT).show();
if (rv.getAdapter() != null)
{
rv.getAdapter().notifyDataSetChanged();
}
}
// Адаптер
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>
{
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
public static class ViewHolder extends RecyclerView.ViewHolder
{
// Номер урока, передается в webactivity
public int mLessonNumber;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view)
{
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString()
{
return super.toString() + " '" + mTextView.getText();
}
}
public String getValueAt(int position)
{
return mValues.get(position);
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items)
{
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
mValues = items;
}
// Создаем холдер с полезной нагрузкой
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
//Создаем список уроков
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.mLessonNumber = position + 1;
// Увеличиваем позицион на 1 что не было 0 урока
holder.mTextView.setText((position + 1) + " " + mValues.get(position));
// Если урок пройден
String finished = sLessonsPref.getString((position + 1) + "", "");
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
//.load(Cheeses.getRandomCheeseDrawable())
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
holder.mTextView.setTextColor(R.color.black);
// holder.mImageView.setVisibility(View.GONE);
}
// Вызов WebActivity
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Context context = v.getContext();
Intent intent = new Intent(context, WebActivity.class);
// Передаем вебвью номер урока и запускаем ее
intent.putExtra(WebActivity.EXTRA_NAME, holder.mLessonNumber);
context.startActivity(intent);
}
});
}
// Определяем количество выводимых строк
#Override
public int getItemCount()
{
return mValues.size();
}
}
}
Implement a reset() method in the adapter that mark all items as "not done" and then try:
LessonsListFragment.rv.getAdapter().reset();
LessonsListFragment.rv.getAdapter().notifyDataSetChanged();
instead of:
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
inside onNavigationItemSelected.
Also, you shouldn't be using static variables (like static RecyclerView rv), use private vars with getters
The problem was in else statement. I added there this code, and now its ok. notifydatachanged work correctly from navigationview
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
Glide.with(holder.mImageView.getContext()).load(R.color.white)
.fitCenter()
.into(holder.mImageView);
holder.mTextView.setTextColor(R.color.black);
}

Android - TabLayout & ViewPager > Fragments > OnListFragmentInteractionListener

I'm new to Android and I started building a "Navigation Drawer Activity" project. I added a TabLayout and ViewPager to my activity_main.xml and now I can swipe between different lists. When I click an item in a list, it calls onListFragmentInteraction in my MainActivity.java. I tried the code below to dynamically add a Detail fragment when a user clicks an item in the list, but I get this error. My MainActivity class does "implement CustomerFragment.OnListFragmentInteractionListener"
First, is my attempt at showing a detail fragment inside a ViewPager correct? Would the code I am attempting below add a fragment in the current tab?
Secondly, does anyone know why I am getting this error?
Thanks so much!
Error:
java.lang.RuntimeException: com.myproject.android.MainActivity#186e12d
must implement OnFragmentInteractionListener
MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, TabLayout.OnTabSelectedListener, CustomerFragment.OnListFragmentInteractionListener, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private TabLayout tabLayout;
private ViewPager viewPager;
private Pager adapter;
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) { }
#Override
public void onTabReselected(TabLayout.Tab tab) { }
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Home"));
tabLayout.addTab(tabLayout.newTab().setText("Customers"));
tabLayout.addTab(tabLayout.newTab().setText("Jobs"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.addOnTabSelectedListener(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FirebaseMessaging.getInstance().subscribeToTopic("global");
String token = FirebaseInstanceId.getInstance().getToken();
// Check Google Play Services
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.build();
// test
Date d = new Date();
DbHandler dbHandler = new DbHandler(this, null, null, 1);
Customer customer = new Customer(1, 1, 1, 1, "Test", "Test", "Test", false, d, 1, d, 1);
dbHandler.addCustomer(customer);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
startActivity(new Intent(this, LoginActivity.class));
} else if (id == R.id.nav_gallery) {
startActivity(new Intent(this, SyncActivity.class));
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Customer List Fragment:
public class CustomerFragment extends Fragment {
private OnListFragmentInteractionListener mListener;
public CustomerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_customer_list, container, false);
SearchView sv = (SearchView) view.findViewById(R.id.searchview);
RecyclerView rv = (RecyclerView) view.findViewById(R.id.recyclerview);
// Adapter
rv.setLayoutManager(new LinearLayoutManager(view.getContext()));
final CustomerAdapter adapter = new CustomerAdapter(getCustomers(), mListener);
rv.setAdapter(adapter);
// Search
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
//adapter.getFilter().filter(query);
return false;
}
});
return view;
}
private ArrayList<Customer> getCustomers() {
DbHandler dbHandler = new DbHandler(this.getActivity(), null, null, 1);
ArrayList<Customer> customers = dbHandler.getCustomers();
return customers;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction(Customer customer);
}
}
Customer Adapter:
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder> {
private final List<Customer> mValues;
private final OnListFragmentInteractionListener mListener;
public CustomerAdapter(List<Customer> items, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_customer, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Customer customer = mValues.get(position);
holder.mItem = customer;
holder.mIdView.setText(String.valueOf(customer.getId()));
holder.mContentView.setText(customer.getCompanyName());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public Customer mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
UPDATE: It looks like I needed to add both onListFragmentInteraction AND onFragmentInteraction. The first is for the CustomerListFragment and the 2nd is for the CustomerDetailFragment.
And to get the CustomerDetailFragment working with the tabs, I followed this and got it working:
https://medium.com/#nilan/separate-back-navigation-for-a-tabbed-view-pager-in-android-459859f607e4#.lrjeexdcp
#Override
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
You need to put
public void onListFragmentInteraction(Customer customer){
FragmentManager fm = getSupportFragmentManager();
CustomerDetailFragment fragment = CustomerDetailFragment.newInstance(customer);
fm.beginTransaction().add(R.id.pager, fragment).commit();
}
Inside your MainActivity class instead of outside of it.
If that's not actually how your code is, edit your answer to break up the blocks to accurately represent how your code is built and include your interfance inside the fragment for the listener. You also may need the #Override tag above the onListFragmentInteraction implementation
Edit
As I mentioned above you need to put the #Override tag above the onListFragmentInteraction implementation, look at every other listener implementation you already have.

Android Fragment replace onClick as well as the selected tab to be change

I have a MainActivity which has AppBar containing toolbar and TabLayout, and also ViewPager.
MainActivity holds 4 fragments home, cash, card and account.
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private AppBarLayout appBarLayout;
Window window;
#Override
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(this.getResources().getColor(R.color.color_primary_green_dark));
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setTitle("Example Wallet");
toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(getBaseContext(), "Tab " + position + " Onpage Selected " + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show();
if (position == 0) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
}
} else if (position == 1) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
tabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
} else if (position == 2) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_yellow_dark));
}
} else if (position == 3) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_red_dark));
}
} else {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab);
if (fab1 != null) {
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerIntent = new Intent(MainActivity.this, Detail.class);
startActivity(registerIntent);
}
});
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentMain(), "Home");
adapter.addFrag(new FragmentCash(), "Cash");
adapter.addFrag(new FragmentCard(), "Card");
adapter.addFrag(new FragmentAccount(), "Account");
adapter.addFrag(PartThreeFragment.createInstance(20), "Tab1");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return mFragmentTitleList.get(position);
}
}
}
home fragment code
public class FragmentMain extends Fragment {
private List<Movie> movieList1 = new ArrayList<>();
private List<Movie> movieList2 = new ArrayList<>();
private RecyclerView recyclerView,recyclerView1;
private MovieAdapter mAdapter1,mAdapter2;
private LinearLayout cash_layout,card_layout,account_layout;
private ViewGroup c;
public FragmentMain() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.content_main, container, false);
//final android.app.ActionBar actionBar = getActivity().getActionBar();
//c=container;
recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
cash_layout = (LinearLayout) v.findViewById(R.id.linearLayout_cash_bal);
card_layout = (LinearLayout) v.findViewById(R.id.linearLayout_card_bal);
account_layout = (LinearLayout) v.findViewById(R.id.linearLayout_account_bal);
mAdapter1 = new MovieAdapter(movieList1);
RecyclerView.LayoutManager mLayoutManager1 = new LinearLayoutManager(v.getContext());
recyclerView.setLayoutManager(mLayoutManager1);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter1);
prepareMovieData1();
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
getContext().getActionBar().setSelectedNavigationItem(2);
/*actionBar.selectTab(actionBar.getTabAt(1));
FragmentManager fm=getFragmentManager();
fm.beginTransaction().replace(R.layout.content_cash, (Fragment)new FragmentCash()).commit();
getActivity().getActionBar().setTitle("Home");
//ActionBar actionBar = getActivity().getActionBar();*/
/*FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();*/
}
});
/*mAdapter2 = new MovieAdapter(movieList2);
RecyclerView.LayoutManager mLayoutManager2 = new LinearLayoutManager(v.getContext());
recyclerView1.setLayoutManager(mLayoutManager2);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.setAdapter(mAdapter2);
prepareMovieData2();*/
return v;
}
private void prepareMovieData1() {
movieList1.clear();
Movie movie = new Movie("info","List is empty", "To create an item, click on (+) button", "","");
movieList1.add(movie);
mAdapter1.notifyDataSetChanged();
}
/*public void onClick1(View v) {
FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}*/
/*private void prepareMovieData2() {
Movie movie = new Movie("card","Card", "New Dress", "Rs.50.00","11/09/2016");
movieList2.add(movie);
mAdapter2.notifyDataSetChanged();
}*/
}
I am trying to call cash, card and account fragment from home fragment but this code
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
adds other fragment with home fragment visible.
The solution I need is, in the below image when I click the cash balance it slide to the cash tab with cash fragment onscreen.
It looks like you are trying to add the cash fragment on top of the view pager, or replace it all together. Instead of replacing it in the current view, I'm assuming you would like to navigate to it within the viewPager.
To do that, replace all of your onClick code with pager.setCurrentItem(//Page number with cash fragment on it)
So, your onClick would look something like this:
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
((MainActivity) getActivity()).getViewPager().setCurrentItem(//Your desired page number as int);
}
});
Or you could solve this easily with an interface.
Just create an interface to access your viewPager's operations like so.
public interface ViewPagerInterface {
ViewPager getViewPager();
}
Have your activity implement it:
public MainActivity extends AppCompatActvity implements ViewPagerInterface {
#Override
public ViewPager getViewPager() {
return this.viewPager;
}
}
Then pass that interface to your Fragments and call the getViewPager method.
viewPagerInterface.getViewPager().setCurrentItem(<my-int>);

Fragment disappearing when coming back from another Fragment

I have a viewpager with 3 fragments to make a swipeable widget. When I first load the app they show properly and all the click events work as expected. Same with hitting the back button after clicking each OnClick, sends me back to landingpagenotlogged in and the viewpager/fragments are displayed as expected. My problem is when I hit my menu button and come back to the landing page my view pager disappears.
I did try to use getChildFragmentManager() when setting the adapter and it works but then my onClick events do not work any more as I get no view to id *******.
I have also tried to place the adapter in the onResume(); with no luck at all.
Along with the viewpager, my viewpagerindicator is not working for the homewidget but working for the carousel. Not sure if that is the code or the layout. But I set it up the same way as the carousel and still not seeing it within the screen when run.
Landingpagenotlogged
public class LandingPageFragmentLoggedOut extends LandingPageFragment {
private static final String TAG = LandingPageFragmentLoggedOut.class.getSimpleName();
private ViewPager viewPager;
private RelativeLayout myStoreTab;
private Button signIn;
private final static Fragment instance = new LandingPageFragmentLoggedOut();
LoggedOutWidgetAdapter mAdapter;
ViewPager mPager;
public static final int ITEMS = 3;
static public Fragment getInstance() {
return instance;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
setShoppingListFocusChangeListener();
setSignInBtnClickListener();
super.setViewPagerMotionListeners(viewPager);
setMenuTouchListener();
setTabClickListener();
return view;
}
#Override
protected void inflateFragmentView(LayoutInflater inflater, ViewGroup container) {
view = inflater.inflate(R.layout.landingpage_not_logged_in, container,
false);
RelativeLayout thisLayout = (RelativeLayout) view
.findViewById(R.id.landingpage_logged_out_parent_layout);
TileBackground.fixBackgroundRepeat(thisLayout);
imgArch = view.findViewById(R.id.frag_tab);
}
private void setSignInBtnClickListener() {
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> params = new HashMap<>();
Intent intent = new Intent(getActivity(), SignInActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(
R.anim.enter_in_from_bottom, R.anim.anim_static);
params.put("Module", "Home");
FlurryAgent.logEvent(FlurryConstants.GOTO_SIGN_IN, params);
}
});
}
private void setTabClickListener() {
myStoreTab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tabSelection = 1;
tabSelectionListener.onTabSelectionListener(tabSelection);
toggleStoreTabIndicator(1);
}
});
}
#Override
#SuppressLint("WrongViewCast")
protected void setUIreferences() {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
overlay = view.findViewById(R.id.landingpage_screenOverlay);
indicator = (LinePageIndicator) view.findViewById(R.id.image_slider_indicator);
this.signIn = (Button) view.findViewById(R.id.landingpg_sign_in_btn);
shoppingListBtn = (ImageView) view.findViewById(R.id.icnlistoptions);
myStoreTab = (RelativeLayout) view.findViewById(R.id.frag_tab);
menuButton = (Button) view.findViewById(R.id.imgBanner_list);
logoButton = (ImageView) view.findViewById(R.id.headerLogo);
addShoppingListItemWidget = (EditText) view.findViewById(R.id.editAddItemNotLoggedIn);
addShoppingListItemWidget.setOnKeyListener(null);
addedItemConfirmation = view.findViewById(R.id.addedItemConfirmation);
imgScanner = (ImageView) view.findViewById(R.id.imgScannerNotLoggedIn);
toggleScannerVisibility(true);
itemAddedText = (TextView) view.findViewById(R.id.item_added_text);
weeklyAdImg = (ImageView) view.findViewById(R.id.weeklyad_img);
defaultWelcomeMsg = (ImageView) view.findViewById(R.id.landing_page_default_img);
setWeeklyAdThumbNail();
if(imgUrl!=null)
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
//setWeeklyAdOnClickListener();
setWeeklyAdClickListener();
couponsGrid = view.findViewById(R.id.coupons_grid);
couponsPlaceholderImg = (ImageView) view.findViewById(R.id.feat_coupons);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
itemAddedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
}
imgScanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
mShoppingListAdd = (RelativeLayout) view.findViewById(R.id.shoppinglis_shortcut);
mShoppingListAdd.setVisibility(View.GONE);
mAdapter = new LoggedOutWidgetAdapter(getFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(mAdapter);
LinePageIndicator mLoggedOutWidgetIndicator = (LinePageIndicator)view.findViewById(R.id.homewidgetLoggedOutIndicator);
mLoggedOutWidgetIndicator.setViewPager(mPager);
}
// MSM - 214
private void setWeeklyAdThumbNail() {
try {
if (LocalDb.getStoreId() != LocalDb.DEFAULT_VAL) {
if (weeklyAdBundle != null && !weeklyAdBundle.isEmpty()) {
//MSM - 155
if (!Utils.isStringNull(weeklyAdBundle.getString("WeeklyAdThumbnail"))) {
Log.e("BANNER ID SET: ", weeklyAdBundle.getString("WeeklyAdThumbnail"));
imgUrl = weeklyAdBundle.getString("WeeklyAdThumbnail");
}
else
imgUrl = weeklyAdBundle.getString("0FirstThumbnail");
}
}
if (urls == null || !urls.contains(imgUrl)) {
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
}
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
jsonParser = new CarouselJSONParser(this);
jsonParser.execute();
} else {
setDefaultOfflineImage();
weeklyAdImg.setImageResource(R.drawable.img_ad_default);
// TODO Set OFFLINE message here
}
}
#Override
public void setCarouselData(ArrayList<CarouselImageData> imageDatas) {
Log.v(TAG, "Set Carousel Data hit");
if (imageDatas != null) {
this.advertisements = imageDatas;
runnable(advertisements.size());
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
viewPager
.setAdapter(new ImageSliderAdapter(activity, imageDatas, this, weeklyAdBundle));
indicator.setViewPager(viewPager);
if (isFirstTimeLaunched) {
fadeInWelcomMsg();
Log.v(TAG, "first time launched, welcome message initaited");
} else {
viewPager.setVisibility(View.VISIBLE);
indicator.setVisibility(View.VISIBLE);
Log.v(TAG, "Returning user, viewpager set visible");
}
} else {
setDefaultOfflineImage();
}
}
#Override
public void onResume() {
if (LocalDb.isLoggedIn()) {
Fragment fragment = new LandingPageFragment();
launchNavigationItemFragment(fragment);
}
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
if (viewPager == null) {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
}
mAdapter = new LoggedOutWidgetAdapter(getChildFragmentManager());
super.onResume();
if (newItemIsAdded) {
onShoppingListResult();
}
// addShoppingListItemWidget.clearFocus();
}
#Override
void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
#Override
public void run() {
if (!pageIsSliding) {
if (viewPager.getCurrentItem() == size - 1) {
viewPager.setCurrentItem(0);
} else {
viewPager.setCurrentItem(
viewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
}
}
};
}
#Override
void toggleStoreTabIndicator(int tab) {
if (storeTabIsClosed) {
storeTabIsClosed = false;
imgArch.setBackgroundResource(R.drawable.img_single_arch_my_store);
} else {
storeTabIsClosed = true;
imgArch.setBackgroundResource(R.drawable.img_arch);
}
}
#Override
protected void setFontsOnTextViews(View view) {
}
#Override
protected void setTabClickListeners() {
}
#Override
public void setViewPagerMotionListeners(ViewPager vPager) {
}
public class LoggedOutWidgetAdapter extends FragmentPagerAdapter {
public LoggedOutWidgetAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ProductLocatorHomeWidgetFragment.init(position);
case 1:
return ProductScanHomeWidgetFragment.init(position);
case 2:
return MyShoppingListHomeWidgetFragment.init(position);
default:
return null;
}
}
#Override
public int getCount() {
return ITEMS;
}
}
}
The three fragments that are tied to the viewpager
ProductLocatorHomeWidgetFragment
public class ProductLocatorHomeWidgetFragment extends Fragment {
int fragVal;
int storeId;
String storeName, storeLat, storeLong, retail_store_id;
TextView mProductLocatorClickZone;
StoreList sList;
public static ProductLocatorHomeWidgetFragment init(int val) {
ProductLocatorHomeWidgetFragment productLocatorFragment = new ProductLocatorHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodLocator", val);
productLocatorFragment.setArguments(args);
return productLocatorFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("prodLocator") : 1;
sList = new StoreList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_locator_search_widget, container, false);
mProductLocatorClickZone = (TextView) layoutView.findViewById(R.id.editSearchItemNotLoggedIn);
mProductLocatorClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sList = LandingPageFragment.storeList;
if(sList.getId() != null){
storeId = Integer.parseInt(sList.getId());
storeLat = sList.getLatitude();
storeLong = sList.getLongitude();
storeName = sList.getName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
else if (sList.getId() == null) {
if (LocalDb.getStoreId() > 0) {
storeId = LocalDb.getStoreId();
storeLat = LocalDb.getStoreLat();
storeLong = LocalDb.getStoreLng();
storeName = LocalDb.getMyStoreName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
}
else {
StoreLocatorDetailsSearchFragment storeLocatorDetailsSearchFragment = new StoreLocatorDetailsSearchFragment();
Bundle b1 = new Bundle();
b1.putInt("currentFragment", 10);
storeLocatorDetailsSearchFragment.setArguments(b1);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, storeLocatorDetailsSearchFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return layoutView;
}
}
MyShoppingListHomeWidgetFragment
public class MyShoppingListHomeWidgetFragment extends Fragment {
int fragVal;
EditText mShoppingListClickZone;
ImageView mShoppinglistScanClickZone;
public static MyShoppingListHomeWidgetFragment init(int val) {
MyShoppingListHomeWidgetFragment myShoppingListFragment = new MyShoppingListHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("myShoppingList", val);
myShoppingListFragment.setArguments(args);
return myShoppingListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("myShoppingList") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.shopping_list_widget, container, false);
mShoppingListClickZone = (EditText) layoutView.findViewById(R.id.editAddItemNotLoggedIn);
mShoppingListClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingListItemsFragment shoppingListItemsFragment = new ShoppingListItemsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, shoppingListItemsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
mShoppinglistScanClickZone = (ImageView) layoutView.findViewById(R.id.imgScannerNotLoggedIn);
mShoppinglistScanClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
return layoutView;
}
}
ProductScanHomeWidgetFragment
public class ProductScanHomeWidgetFragment extends Fragment {
int fragVal;
LinearLayout mCouponSearchClickZone, mRefillPrescriptionClickZone;
View mDivider;
public static ProductScanHomeWidgetFragment init(int val) {
ProductScanHomeWidgetFragment productScanFragment = new ProductScanHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodScan", val);
productScanFragment.setArguments(args);
return productScanFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("prodScan") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_scan_widget, container, false);
mRefillPrescriptionClickZone = (LinearLayout) layoutView.findViewById(R.id.refillPrescriptionClickZone);
mCouponSearchClickZone = (LinearLayout) layoutView.findViewById(R.id.couponSearchClickZone);
mCouponSearchClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ECouponsViewFragment eCouponsViewFragment = new ECouponsViewFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, eCouponsViewFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
if (LocalDb.getBannerSupportRefillPrescriptions().equalsIgnoreCase(
UtilConstants.KEY_WORD_FALSE)) {
mDivider = layoutView.findViewById(R.id.divider);
mDivider.setVisibility(View.GONE);
mRefillPrescriptionClickZone.setVisibility(View.GONE);
} else {
mRefillPrescriptionClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPharmacyFragment addPharmacyFragment = new AddPharmacyFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, addPharmacyFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
return layoutView;
}
}
I was able to solve this using a FragmentStatePagerAdapter and not the FragmentPagerAdapter.
So I removed the old FragmentPagerAdapter in LadingPageLoggedOut and replaced it with
inal String [] fragmentClasses = {"com.supervalu.mobile.android.HomeScreenWidget.ProductLocatorHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.ProductScanHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.MyShoppingListHomeWidgetFragment"};
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragmentAtPosition = null;
// Check to make sure that your array is not null, size is greater than 0 ,
// current position is greater than equal to 0, and position is less than length
if((fragmentClasses != null) && (fragmentClasses.length > 0)&&(position >= 0)&& (position < fragmentClasses.length))
{
// Instantiate the Fragment at the current position of the Adapter
fragmentAtPosition = Fragment.instantiate(getContext(), fragmentClasses[position]);
fragmentAtPosition.setRetainInstance(true);
}
return fragmentAtPosition;
}
#Override
public int getCount() {
return fragmentClasses.length;
}
});

Categories

Resources