I am developing an app which have a single activity and several fragments.
The first fragment contains a viewpager which have 3-4 fragments extra. I can switch from one fragment to another easily and the viewpager works fine, but when i am going back from one fragment to the first(not in viewpager), the viewpager is not loading all fragments. Below is the code:
mainactivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private DrawerLayout loginlayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
private Fragment mFragment = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1= (Button) findViewById(R.id.button1);
Button btn2= (Button) findViewById(R.id.button2);
Button login= (Button) findViewById(R.id.login);
Button about= (Button) findViewById(R.id.about);
about.setOnClickListener(this);
login.setOnClickListener(this);
btn2.setOnClickListener(this);
btn1.setOnClickListener(this);
FontChangeCrawler fontChanger = new FontChangeCrawler(getAssets(), "fonts/font.ttf");
fontChanger.replaceFonts((ViewGroup)this.findViewById(android.R.id.content));
if (findViewById(R.id.content_frame) != null) {
if (savedInstanceState != null) {
return;
}
FirstFragment firstFragment = new FirstFragment();
firstFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().addToBackStack(null)
.add(R.id.content_frame, firstFragment).commit();
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setCustomView(R.layout.actionbar_image);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#662e91")));
mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
});
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
FirstFragment firstFragment = new FirstFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new FirstFragment()).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
case R.id.login:
callLoginDialog();
break;
case R.id.about:
about abt = new about();
abt.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame, abt).commit();
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
}
}
public class FontChangeCrawler
{
private Typeface typeface;
public FontChangeCrawler(Typeface typeface)
{
this.typeface = typeface;
}
public FontChangeCrawler(AssetManager assets, String assetsFontFileName)
{
typeface = Typeface.createFromAsset(assets, "fonts/font.ttf");
}
public void replaceFonts(ViewGroup viewTree)
{
View child;
for(int i = 0; i < viewTree.getChildCount(); ++i)
{
child = viewTree.getChildAt(i);
if(child instanceof ViewGroup)
{
// recursive call
replaceFonts((ViewGroup)child);
}
else if(child instanceof TextView)
{
// base case
((TextView) child).setTypeface(typeface);
}
}
}
}
public void callLoginDialog()
{
Dialog myDialog = new Dialog(this);
myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myDialog.setContentView(R.layout.loginwindow);
myDialog.setCancelable(false);
TextView reg= (TextView) myDialog.findViewById(R.id.register);
Button login = (Button) myDialog.findViewById(R.id.login);
EditText emailaddr = (EditText) myDialog.findViewById(R.id.editText2);
EditText password = (EditText) myDialog.findViewById(R.id.editText3);
myDialog.show();
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Register",
Toast.LENGTH_LONG).show();
}
});
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//your login calculation goes here
}
});
myDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.cancel();
return true;
}
return false;
}
});
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
}
else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.user:
mDrawerLayout.closeDrawer(Gravity.LEFT);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
firstfragment.java
public class FirstFragment extends Fragment {
public ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first,
container, false);
viewPager = (ViewPager) rootView.findViewById(pager);
viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager()));
viewPager.setCurrentItem(0);
PagerTitleStrip pagerTitleStrip= (PagerTitleStrip) rootView.findViewById(R.id.titlestrip);
pagerTitleStrip.setNonPrimaryAlpha(Float.parseFloat("0.3"));
viewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
#Override
public void transformPage(View view, float position) {
final float normalizedposition = Math.abs(Math.abs(position) - 1);
view.setAlpha(normalizedposition);
}
});
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
for (int counter = 0 ; counter<pagerTitleStrip.getChildCount(); counter++) {
if (pagerTitleStrip.getChildAt(counter) instanceof TextView) {
((TextView)pagerTitleStrip.getChildAt(counter)).setTypeface(font);
}
}
return rootView;
}
}
viewpageadapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 4;
// Tab Titles
private String tabtitles[] = new String[] { "Home", "Men", "Women", "Children" };
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
SecondFragment fragmenttab1 = new SecondFragment();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
ThirdFragment fragmenttab2 = new ThirdFragment();
return fragmenttab2;
case 2:
Fourthfragment fragmenttab3 = new Fourthfragment();
return fragmenttab3;
case 3:
FifthFragment fragmenttab4 = new FifthFragment();
return fragmenttab4;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
Try changing viewPager.setAdapter(new ViewPagerAdapter(getFragmentManager())); with viewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
Related
I want to retrieve image for recycler view in fragment
code of MovieActivity :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
`
code for HomeFragment :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Intent intent = new Intent(this, LoadingActivity.class);
startActivity(intent);
setupViewFragment();
}
setupToolbar();
setupBottomNavigation();
}
private void setupViewFragment() {
// show discover movies fragment by default
DiscoverMoviesFragment discoverMoviesFragment = DiscoverMoviesFragment.newInstance();
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), discoverMoviesFragment, R.id.fragment_container);
}
private void setupBottomNavigation() {
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.action_home:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), HomeFragment.newInstance(),
R.id.fragment_container);
//startActivity(new Intent(getApplicationContext()
//,HomeActivity.class));
return true;
case R.id.action_discover:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), DiscoverMoviesFragment.newInstance(),
R.id.fragment_container);
return true;
case R.id.action_favorites:
ActivityUtils.replaceFragmentInActivity(
getSupportFragmentManager(), FavoritesFragment.newInstance(),
R.id.fragment_container);
return true;
}
return false;
}
});
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
}
code for HomeAdapter :
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private OnItemClickListener mListener;
public HomeAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getName());
Picasso.get()
.load(uploadCurrent.getImageUrl())
.placeholder(R.mipmap.ic_launcher)
.centerInside()
.fit()
.into(holder.imageView);
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
public TextView textViewName;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.text_view_name);
imageView = itemView.findViewById(R.id.image_view_upload);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
doWhatever.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
switch (item.getItemId()) {
case 1:
mListener.onWhatEverClick(position);
return true;
case 2:
mListener.onDeleteClick(position);
return true;
}
}
}
return false;
}
}
public interface OnItemClickListener {
void onItemClick(int position);
void onWhatEverClick(int position);
void onDeleteClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
}
this is the error :
`C:\Users\User\Desktop\PopularMovies\app\src\main\java\com\ajdi\yassin\popularmovies\ui\movieslist\home\HomeFragment.java:65: error: incompatible types: HomeFragment cannot be converted to Context
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);`
Please use getApplicationContext() ,because HomeFragment.this is consider as an Activity and in your HomeAdapter constructor you have passed Context.
Replace:
mAdapter = new HomeAdapter(HomeFragment.this, mUploads);
To:
mAdapter = new HomeAdapter(getApplicationContext(), mUploads);
In my project I have a main activity with 3 fragments that are displayed via a ViewPager in a TabLayout on launch. In one of my fragments I have a RecyclerView and a FAB that, when clicked, launches an alert dialog that captures user input to be displayed in the RV in the fragment. Upon clicking ADD in the dialog, nothing appears in the RV but when I click the FAB and try again, it appears in the RV. So what I am saying, I have to input info in the FAB twice before it displays in my RV in my fragment. So I was wondering if someone could help me understand why this is happening. It seems like my RV in my frag is not being created right away, but all in all my app is not crashing so I have no log to post. I've research but to no avail. I am self taught so any help would be appreciated.
Fragment
public class SubjectsFrag extends DialogFragment implements CardAdapter.ClickListener,
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public CardAdapter cardAdapter;
public SubjectsModel model = null;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper dbHelper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#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_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
cardAdapter = new CardAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(cardAdapter);
return view;
}
#Override
public void itemClicked(View view, int position) {
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel(sTitle, sTeacher);
model.setmTitle(title);
model.setmTeacher(teacher);
subMod.add(model);
cardAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Dialog Fragment
public class SubjectsEditor extends DialogFragment
{
Context context;
private OnAddSubjectListener listener;
#BindView(R.id.main_root)
ViewGroup root;
public interface OnAddSubjectListener
{
void OnAddSubjectSubmit(String title, String teacher);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try{
listener = (OnAddSubjectListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement onAddSubjectListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.editor_subjects, container, false);
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View view = LayoutInflater.from(getActivity()).inflate(R.layout.editor_subjects, root);
final EditText mTitle = view.findViewById(R.id.edit_subject);
final EditText mTeacher = view.findViewById(R.id.edit_subject_teacher);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view)
.setTitle("Add Subject")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String sTitle = mTitle.getText().toString();
final String sTeacher = mTeacher.getText().toString();
listener.OnAddSubjectSubmit(sTitle, sTeacher);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Recycler Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder>
{
public ArrayList<SubjectsModel> subMod;
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
public CardAdapter(Context context, ArrayList<SubjectsModel> items)
{
this.context = context;
this.subMod = items;
}
#NonNull
#Override
public CardAdapter.CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
return new CardViewHolder(LayoutInflater.from(context).inflate(R.layout.subjects_item_list,
parent, false));
}
#Override
public void onBindViewHolder(final CardAdapter.CardViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
}
public class CardViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public CardViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
clickListener.itemClicked(view, getAdapterPosition());
Toast.makeText(context, R.string.hello_blank_fragment, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public int getItemCount()
{
return subMod.size();
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
CardAdapter.clickListener = clicked;
}
public interface ClickListener
{
public void itemClicked(View view, int position);
}
}
Fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
Main Activity
public class OverviewActivity extends AppCompatActivity
{
private NavigationView mNavigationView;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
CharSequence tabTitles[] = {"SUBJECTS", "TASKS", "CALENDER"};
int numOfTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_nav);
Toolbar toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
final ViewPager viewPager = findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), tabTitles, numOfTabs);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.syncState();
mNavigationView = findViewById(R.id.nav_view);
setupDrawerContent(mNavigationView);
/* FloatingActionButton fab = 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();
}
}); */
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#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
public void onBackPressed()
{
//DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_nav, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem)
{
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.nav_grades:
Intent gradesIntent = new Intent(this, GradesActivity.class);
startActivity(gradesIntent);
break;
case R.id.nav_notes:
Intent notesIntent = new Intent(this, NotesActivity.class);
startActivity(notesIntent);
break;
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawer.closeDrawer(GravityCompat.START);
}
}
Using notifyDataSetChanged() should do the trick. Check this answer
Giving it a once-over, nothing jumped out. You can use either the debugger or Log.d(String, String) calls to challenge your assumptions about what’s being called when. I’d take a closer look at when you call your adapter’s notifyDataSetChanged() and then at the getItemCount and bind or createViewHolder calls inside the adapter itself.
I am having four tab in my View pager I have search in google but I can,t found any solution when Swipe my view pager it work fine like 1-2-3-4 but when I try to swipe reverse 4-3-2-1 than my data get lost or you can say my adapter get lost.My View Pager is inside Activity.My Data is lost when I go to next page and back then back my data is lost.
My Main Activity is:
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
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);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
My Fragment is
public class ImageListFragment extends Fragment {
String category_Name, Category_ID, Product_ID, Product_Name,
Product_Image, Product_Price, Product_Sale, Cart;
public static final String STRING_IMAGE_URI = "ImageUri";
public static final String STRING_IMAGE_POSITION = "ImagePosition";
private static MainActivity mActivity;
ArrayList<SingleItemModel> singleItemModels;
RecyclerView recyclerView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCategoryone();
Fresco.initialize(getContext());
mActivity = (MainActivity) getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
recyclerView = (RecyclerView) inflater.inflate(R.layout.layout_recylerview_list, container, false);
return recyclerView;
}
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder> {
// private String[] mValues;
private ArrayList<SingleItemModel> mValues;
private RecyclerView mRecyclerView;
public static class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final SimpleDraweeView mImageView;
public final LinearLayout mLayoutItem;
public final ImageView mImageViewWishlist;
TextView iTemName, itemDescription, itemPrice;
public ViewHolder(View view) {
super(view);
mView = view;
mImageView = (SimpleDraweeView) view.findViewById(R.id.image1);
mLayoutItem = (LinearLayout) view.findViewById(R.id.layout_item);
mImageViewWishlist = (ImageView) view.findViewById(R.id.ic_wishlist);
iTemName = (TextView) view.findViewById(R.id.itemName);
itemDescription = (TextView) view.findViewById(R.id.itemDescription);
itemPrice = (TextView) view.findViewById(R.id.itemPrice);
}
}
public SimpleStringRecyclerViewAdapter(RecyclerView recyclerView, ArrayList<SingleItemModel> items) {
mValues = items;
mRecyclerView = recyclerView;
}
#Override
public ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder(view);
}
#Override
public void onViewRecycled(ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder) {
if (holder.mImageView.getController() != null) {
holder.mImageView.getController().onDetach();
}
if (holder.mImageView.getTopLevelDrawable() != null) {
holder.mImageView.getTopLevelDrawable().setCallback(null);
//
}
}
#Override
public void onBindViewHolder(final ImageListFragment.SimpleStringRecyclerViewAdapter.ViewHolder holder, final int position) {
SingleItemModel singleItemModel = mValues.get(position);
holder.iTemName.setText(singleItemModel.getCategory_Name());
final Uri uri = Uri.parse(singleItemModel.getProduct_Image());
holder.mImageView.setImageURI(uri);
holder.itemPrice.setText(singleItemModel.getProduct_Price());
holder.itemDescription.setText(singleItemModel.getProduct_Sale());
}
#Override
public int getItemCount() {
return mValues.size();
}
}
public void getCategoryone() {
final RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://proaudiobrands.com/app/feature.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("shabina shopping response", response);
try {
singleItemModels = new ArrayList<>();
JSONObject mainObj = new JSONObject(response);
Log.d("shabina ", response);
JSONArray Feature_product = mainObj.getJSONArray("Feature_product");
for (int i = 0; i < Feature_product.length(); i++) {
JSONObject Feature_Product = Feature_product.getJSONObject(i);
String Category_Namee = Feature_Product.getString("Category_Namee");
String Category_IDs = Feature_Product.getString("Category_IDs");
JSONArray Product_List = Feature_Product.getJSONArray("Product_List");
for (int j = 0; j < Product_List.length(); j++) {
JSONObject Category_Name = Product_List.getJSONObject(j);
if (Category_Name.getString("Category_Name").equals("Microphones")) {
category_Name = Category_Name.getString("Category_Name");
Category_ID = Category_Name.getString("Category_ID");
Product_ID = Category_Name.getString("Product_ID");
Product_Name = Category_Name.getString("Product_Name");
Product_Image = Category_Name.getString("Product_Image");
Product_Price = Category_Name.getString("Product_Price");
Product_Sale = Category_Name.getString("Product_Sale");
Cart = Category_Name.getString("Cart");
Log.e("sushil Category_Name", category_Name + " " + Category_ID + " " + Product_ID + " " + Product_Name + " " + Product_Image + " " + Product_Price + " " + Product_Sale + " " + Cart);
SingleItemModel singleItemModel1 = new SingleItemModel(category_Name, Category_ID, Product_ID, Product_Name, Product_Image, Product_Price, Product_Sale, Cart);
singleItemModels.add(singleItemModel1);
}
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(new ImageListFragment.SimpleStringRecyclerViewAdapter(recyclerView, singleItemModels));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error", error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("method", "feature");
params.put("userId", "PRO1");
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
90000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
}
Replace your MainActivity with below
public class MainActivity extends AppCompatActivity {
public static int notificationCountCart = 0;
Toolbar toolbar;
ActionBar actionBar;
static ViewPager viewPager;
static TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
if (toolbar != null)
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
TextView textView = new TextView(this);
textView.setText("Shopping");
textView.setTextSize(20);
textView.setTypeface(null, Typeface.BOLD);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
textView.setTextColor(getResources().getColor(R.color.white));
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(textView);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(new IconDrawable(this, FontAwesomeIcons.fa_angle_left).colorRes(R.color.white).actionBarSize());
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
viewPager = (ViewPager) findViewById(R.id.viewpagerrr);
viewPager.setOffscreenPageLimit(4);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
invalidateOptionsMenu();
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// Get the notifications MenuItem and
// its LayerDrawable (layer-list)
MenuItem item = menu.findItem(R.id.action_cart);
NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCountCart);
// force the ActionBar to relayout its MenuItems.
// onCreateOptionsMenu(Menu) will be called again.
invalidateOptionsMenu();
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
startActivity(new Intent(MainActivity.this, SearchResultActivity.class));
return true;
} else if (id == R.id.action_cart) {
/* NotificationCountSetClass.setAddToCart(MainActivity.this, item, notificationCount);
invalidateOptionsMenu();*/
startActivity(new Intent(MainActivity.this, CartListActivity.class));
/* notificationCount=0;//clear notification count
invalidateOptionsMenu();*/
return true;
} else if (id == android.R.id.home) {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
// startActivity(new Intent(MainActivity.this, EmptyActivity.class));
}
return super.onOptionsItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
ImageListFragment fragment = new ImageListFragment();
SpeakerFragment speakerFragment = new SpeakerFragment();
adapter.addFragment(fragment, getString(R.string.item_2));
adapter.addFragment(speakerFragment, getString(R.string.item_4));
adapter.addFragment(new HeadPhone(), getString(R.string.item_3));
adapter.addFragment(new Offer(), getString(R.string.item_1));
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
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);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
Hello in my project I am to play a song when I click on a button and this button is is a fragment layout but I don't now if I need to put the code in the fragment or in the MainActivity. So here I put it in the fragment and the "protected" of the protected void is underline in red same for the "(this, resId)". Can someone help thanks a lot.
here is my fragment.java
public class thekairi78 extends Fragment {
private AdView adView;
private MediaPlayer mPlayer = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.thekairi78, container,
false);
Button regarde = (Button) getView().findViewById(R.id.regarde);
regarde.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.regarde);
}
});
adView = new AdView(getActivity());
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.setAdSize(AdSize.SMART_BANNER);
LinearLayout layout = (LinearLayout) rootView.findViewById(R.id.layout_admob);
layout.addView(adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
return rootView;
}
#Override
protected void onPause() {
if(mPlayer != null && mPlayer.isPlaying()){
mPlayer.pause();
}
super.onPause();
}
private void playSound(int resId){
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = MediaPlayer.create(this, resId);
mPlayer.start();
}
}
and here my MainActivity.java
public class MainActivity extends AppCompatActivity {
private MediaPlayer mPlayer = null;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
InterstitialAd mInterstitialAd;
private InterstitialAd interstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdRequest adRequest = new AdRequest.Builder().build();
interstitial = new InterstitialAd(MainActivity.this);
interstitial.setAdUnitId(getString(R.string.admob_interstitial_id));
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
thekairi78 tab1 = new thekairi78();
return tab1;
case 1:
kenny tab2 = new kenny();
return tab2;
case 2:
autres tab3 = new autres();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "TheKairi78";
case 1:
return "Kenny";
case 2:
return "Autres SoundBox";
}
return null;
}
}
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
protected void onPause() {
if(mPlayer != null && mPlayer.isPlaying()){
mPlayer.pause();
}
super.onPause();
}
private void playSound(int resId){
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = MediaPlayer.create(this, resId);
mPlayer.start();
}
}
Hello everyone I'm developing an app that uses old navigation drawer approach. When I update 'com.android.support:appcompat-v7:23.1.1' to 'com.android.support:appcompat-v7:23.4.0' my navigation drawer not opening.
I debugged code and look for deprecated items but could not find any error code or message. Everything works perfectly but navigation drawer is not opening. Here is my code. Thanks in advance.
MainActivity.class
public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, TapuInterface.IAuthorization {
TapuUtils tapuUtils = new TapuUtils();
String userMail, userPassword;
SharedPreferences.Editor editor;
SharedPreferences preferences;
Tracker mTracker;
Bundle bundle;
String tapuAuth = "false";
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleAnalytics.getInstance(this).setLocalDispatchPeriod(15);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
Countly.sharedInstance().init(this, getString(R.string.countly_server), getString(R.string.countly_key));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,(DrawerLayout) findViewById(R.id.drawer_layout));
ActionBar mActionBar = getSupportActionBar();
assert mActionBar != null;
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF297AA6));
if (savedInstanceState == null) {
bundle = getIntent().getExtras();
userMail = bundle.getString("personname");
userPassword = bundle.getString("personpassword");
tapuAuth = bundle.getString("tapu");
}
TapuCredentials.setUserMail(userMail);
TapuCredentials.setUserPassword(userPassword);
TapuCredentials.setTapuAuth(tapuAuth);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, MainMapFragment.newInstance(position + 1), "MapFragment")
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit_alert))
.setCancelable(true)
.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
LoginActivity.fa.finish();
}
})
.setNegativeButton(getString(R.string.no), null)
.show();
}
#Override
public void onStart() {
super.onStart();
Countly.sharedInstance().onStart();
}
#Override
public void onStop() {
super.onStop();
Countly.sharedInstance().onStop();
}
#Override
protected void onResume() {
super.onResume();
mTracker.setScreenName(getResources().getString(R.string.main_screen));
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
Here is my NavigationDrawer.class
public class NavigationDrawerFragment extends Fragment {
private static NavigationDrawerAdapter myAdapter;
public static ArrayList<ListItem> myItems = new ArrayList<>();
public static UserCredentials mUserCredentials = new UserCredentials();
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private DynamicListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
static LegendFragment frLegend = new LegendFragment();
Button mEditLayers, mShowLegend;
String personName,userType,tapucontrol;
TextView mLayersText;
static FragmentManager fragmentManager;
Bundle extras;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
if (savedInstanceState == null) {
extras = getActivity().getIntent().getExtras();
if(mUserCredentials.getUserName()==null || mUserCredentials.getPassword()==null){
mUserCredentials.setUserAccount(extras.getString("username"), extras.getString("password"));
}
personName = extras.getString("personname");
userType = extras.getString("usertype");
tapucontrol = extras.getString("tapu");
}
mDrawerListView = (DynamicListView) rootView.findViewById(R.id.dynamiclistivew);
mLayersText = (TextView) rootView.findViewById(R.id.textview_layers);
myAdapter = new NavigationDrawerAdapter(getActivity(), myItems);
mDrawerListView.setAdapter(myAdapter);
fragmentManager = getFragmentManager();
mDrawerListView.setCheeseList(myItems);
mDrawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mEditLayers = (Button) rootView.findViewById(R.id.button);
mShowLegend = (Button) rootView.findViewById(R.id.legendbutton);
mEditLayers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEditLayers.getText().equals("Düzenle")) {
myAdapter.setEditMode(true);
mEditLayers.setText(getActivity().getString(R.string.ok));
} else {
myAdapter.setEditMode(false);
mEditLayers.setText(getActivity().getString(R.string.editlayers));
}
}
});
return rootView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
null, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
FragmentTransaction ft = fragmentManager.beginTransaction();
if (frLegend.isAdded()) {
ft.remove(frLegend);
ft.commitAllowingStateLoss();
mEditLayers.setVisibility(View.VISIBLE);
mLayersText.setText("Katmanlar");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
// showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
Intent s = new Intent(getActivity(), SearchMainActivity.class);
s.putExtra("username", mUserCredentials.getUserName());
s.putExtra("password", mUserCredentials.getPassword());
s.putExtra("tapu",tapucontrol);
startActivity(s);
break;
case R.id.action_basemaps:
Intent cb = new Intent(getActivity(), BaseMapsActivity.class);
startActivity(cb);
break;
case R.id.action_addlayer:
if (isNetworkAvailable(getActivity())) {
Intent al = new Intent(getActivity(), AddLayerActivity.class);
al.putExtra("usertype", userType);
startActivity(al);
} else {
Toast.makeText(getActivity(), "Lütfen internet bağlantınızı kontrol ediniz.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_about:
Intent au = new Intent(getActivity(), AboutActivity.class);
au.putExtras(extras);
startActivity(au);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class ListItem {
String textdata;
Integer progress;
public ListItem(String textdata, int progress) {
this.textdata = textdata;
this.progress = progress;
}
public boolean equals(Object o) {
ListItem ndListItemObject = (ListItem) o;
return this.textdata.equalsIgnoreCase(ndListItemObject.textdata);
}
}
public void addLayersection(String name, int progress) {
ListItem listItem = new ListItem(name, progress);
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.contains(listItem)) {
myItems.remove(listItem);
} else {
myItems.add(0, listItem);
}
}
}
myAdapter.notifyDataSetChanged();
}
public int getListSizee() {
return myItems.size();
}
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
The Drawer is locked.
Change
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
to
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
Here is the late solution that I find with myself. drawerOpenCloseControl is boolean flag. I am controlling true or false. And then open and close manually.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(drawerOpenCloseControl){
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
drawerOpenCloseControl = false;
}
else{
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerOpenCloseControl = true;
}
break;
}
return super.onOptionsItemSelected(item);
}