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.
Related
How to implement like button hitting count in RecyclerView. I have already created a like button and counter TextView with this code but when I hit the like button the application crashes. This is my code, what's wrong? I am using toggle button for like option and a TextView for counting like hitting.
This is my viewholder
public class WritingsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView MainTitle;
public ImageView Mainimage;
public ImageView Profimage;
public TextView ProfName;
public TextView txv;
public ToggleButton liketglbtn;
public TextView MainDesc, Idvkanme;
private ItemClickListner itemClickListner;
public void setItemClickListner(ItemClickListner itemClickListner) {
this.itemClickListner = itemClickListner;
}
public WritingsViewHolder(View itemView) {
super(itemView);
MainTitle = (TextView)itemView.findViewById(R.id.RTitle);
Mainimage = (ImageView)itemView.findViewById(R.id.rImageView);
Profimage = (ImageView)itemView.findViewById(R.id.Profile_Image);
ProfName = (TextView)itemView.findViewById(R.id.Prof_Name);
MainDesc = (TextView)itemView.findViewById(R.id.rDescriptionTv);
Idvkanme = (TextView)itemView.findViewById(R.id.Idavaka_Name);
txv = (TextView)itemView.findViewById(R.id.tx);
liketglbtn = (ToggleButton) itemView.findViewById(R.id.likeToggleBtn);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
itemClickListner.onClick(v,getAdapterPosition(),false);
}
}
This is my activity
public class WritingsActivity extends AppCompatActivity {
RecyclerView recyclerView;
FirebaseRecyclerOptions<IdavakaModel> options;
FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder> adapter;
DatabaseReference MCC;
String categoryId = "";
RecyclerView.LayoutManager layoutManager;
TextView smsCountText;
int pendingSMSCount = 10;
static Button notifCount;
static int mNotifCount = 0;
Button FBcard, YoutubeCard;
private static final String APP_ID = "ca-app-pub-8867939169855032~9998384849";
Button mSaveBtn, mShareBtn;
private long backPressedTime;
private Toast backToast;
private int mCounter = 0;
ToggleButton btn;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_writings);
FBcard = (Button) findViewById(R.id.button1);
FBcard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(WritingsActivity.this, IdavakaNewsUploadActivity.class);
startActivity(toy);
WritingsActivity.this.finish();
}
});
MobileAds.initialize(this,APP_ID);
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
//Bottom Navigation Bar
final BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.botmnavigation);
bottomNavigationView.setSelectedItemId(R.id.action_privacy);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.myhome:
startActivity(new Intent(getApplicationContext(),MainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_notification:
startActivity(new Intent(getApplicationContext(),ChristianNewsMainActivity.class));
overridePendingTransition(0,0);
return true;
case R.id.action_privacy:
return true;
}
return false;
}
});
MCC= FirebaseDatabase.getInstance().getReference().child("Writings");
recyclerView = (RecyclerView) findViewById(R.id.readingroom_recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
LoadData(categoryId);
}
private void LoadData(String categoryId) {
options = new FirebaseRecyclerOptions.Builder<IdavakaModel>().setQuery(MCC,IdavakaModel.class).build();
adapter = new FirebaseRecyclerAdapter<IdavakaModel, WritingsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull WritingsViewHolder writingsViewHolder, int i, #NonNull IdavakaModel idavakaModel) {
writingsViewHolder.MainTitle.setText(idavakaModel.getTitle());
writingsViewHolder.MainDesc.setText(idavakaModel.getDesc());
writingsViewHolder.ProfName.setText(idavakaModel.getProfname());
writingsViewHolder.Idvkanme.setText(idavakaModel.getIdavakaname());
Picasso.get().load(idavakaModel.getPostimage())
.into(writingsViewHolder.Mainimage);
Picasso.get().load(idavakaModel.getProfimage())
.into(writingsViewHolder.Profimage);
writingsViewHolder.setItemClickListner(new ItemClickListner() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent detailsIntent = new Intent(WritingsActivity.this, IdavakaDetailActivity.class);
detailsIntent.putExtra("CategoryId", adapter.getRef(position).getKey());
startActivity(detailsIntent);
}
});
writingsViewHolder.liketglbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCounter++;
txv.setText(Integer.toString(mCounter));
}
});
}
#NonNull
#Override
public WritingsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.writngs_items, parent, false);
return new WritingsViewHolder(v);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
backToast.cancel();
super.onBackPressed();
WritingsActivity.this.finish();
return;
} else {
backToast = Toast.makeText(getBaseContext(), "See You Soon", Toast.LENGTH_SHORT);
backToast.show();
}
backPressedTime = System.currentTimeMillis();
WritingsActivity.this.finish();
}
public void onCustomToggleClick (View view) {
Toast.makeText(this, "Liked",Toast.LENGTH_SHORT).show();
}
}
You are getting NullPointerException because the TextView you are using is in Activity named txv where you are setting counter. But the problem is you have declared TextView in Activity but have not initialized anywhere in the Activity. You MUST initialize that variable via findViewbyId method before setting values.
Furthermore, you have initialized txv TextView and accessing on Activity that is why you are getting NLP. TextView is a part of Activity layout which you have not Initialized. On the hand you have initialized txv in Adapter which is of no use.
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);
}
}
}
I know that this question is asked many times but we have different situation. Regarding the project I downloaded the project navigation drawer demo from GitHub.com. Provided the code below:
this is the main activity:
package edu.ejapp.dotalegitstore;
#SuppressLint("NewApi")
public class MainActivity extends BaseActivity {
FragmentStackManager fm,sliding_menu;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
setUpView();
menuToggeleSetUp(savedInstanceState);
}
void setUpView(){
fm = new FragmentStackManager(this);
sliding_menu = new FragmentStackManager(this);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
fm.addFragment(new MainFragment(), R.id.main_frame, false, FragmentTransaction.TRANSIT_NONE, false);
sliding_menu.addFragment(new SlidingMenuFragment(), R.id.slide_fragment, false, FragmentTransaction.TRANSIT_NONE, false);
}
void menuToggeleSetUp(Bundle savedInstanceState){
mDrawerToggle = new ActionBarDrawerToggle(this, drawer,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name
) {
#SuppressLint("NewApi")
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
drawer.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
}
}
#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
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (id == R.id.action_settings) {
return true;
}
else if (id == R.id.action_exit) {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle("COnfirm exit");
dialog.setMessage("Are you sure you want to exit?");
dialog.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.setNegativeButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
finish();
}
});
AlertDialog alertDialog = dialog.create();
alertDialog.show();
}
else if (id == R.id.action_login) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
else {
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The base activity extended by MainActivity:
package edu.ejapp.dotalegitstore;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
#SuppressWarnings("deprecation")
public class BaseActivity extends ActionBarActivity{
public ActionBarDrawerToggle mDrawerToggle;
public DrawerLayout drawer;
CharSequence mDrawerTitle;
CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActionBar();
}
public void setActionBar(){
getSupportActionBar().setTitle("");
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(this.getResources().getColor(R.color.app_main)));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
}
and lastly the sliding fragment activity, here the on item click is implemented not in baseactivity or main which is the reason of my problem: i cant close the drawer when i clicked item on the drawer:
public class SlidingMenuFragment extends Fragment {
List<String> data;
ListView list_view;
SlidingMenuListAdapter adapter;
#SuppressLint("InflateParams")
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_sliding_menu, null);
setUpView(root);
return root;
}
void setUpView(ViewGroup root){
list_view = (ListView)root.findViewById(R.id.list_view);
initList();
setUpClick();
}
void initList(){
data = new ArrayList<String>();
data.add("Home");
data.add("Arcana");
data.add("Courrier");
data.add("Hero Sets");
data.add("Immortals");
adapter = new SlidingMenuListAdapter(getActivity(),data);
list_view.setAdapter(adapter);
}
void setUpClick(){
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"Hi "+position,Toast.LENGTH_SHORT).show();
}
});
}
}
I didnt include the other files such as the xmls. My question is:
How can I close the drawer when I clicked item of the list view provided that the onitemclick is defined in SlidingMenuFragment class and the mDrawerlayout is located in BaseActivity class which is extended by MainActivity class?
create a method to close drawer in your main activity and call it from fragment.
public static void closeDrawer(){
if(drawerLayout.isDrawerOpen(leftDrawerList)){
drawerLayout.closeDrawer(leftDrawerList);
}
}
Inside Fragment
MainActivity.closeDrawer();
here is my suggestion:
provide an interface in SlidingMenuFragment like:
public class SlidingMenuFragment extends Fragment {
private OnListItemClickListener mOnListItemClickListener;
//here is mOnListItemClickListener getter and setter method
public *** set(get)OnListItemClickListener(){};
//define a interface here
public interface OnListItemClickListener{
public void onListenItemClick();
}
.
.
.
void setUpClick(){
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(mOnListItemClickListener != null){
mOnListItemClickListener.onListenItemClick();
}
}
});
}
}
and then you should implement this interface in your MainActivity class like:
public class MainActivity extends BaseActivity {
void setUpView(){
fm = new FragmentStackManager(this);
sliding_menu = new FragmentStackManager(this);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
fm.addFragment(new MainFragment(), R.id.main_frame, false, FragmentTransaction.TRANSIT_NONE, false);
SlidingMenuFragment smFragment = new SlidingMenuFragment()
smFragment.setMonListItemClickListener(new OnListItemClickListener(){
public void onListenItemClick(){
drawer.close();
}
});
sliding_menu.addFragment(smFragment, R.id.slide_fragment, false, FragmentTransaction.TRANSIT_NONE, false);
}
}`
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()));
I was having some problem when trying to make my navigation drawer in Android accessible from all Activity. I have a NavigationDrawer.java:
public class NavigationDrawer extends Activity {
static Context context;
private DrawerLayout mDrawerLayout;
private ExpandableListView mDrawerList;
private LinearLayout navDrawerView;
CustomExpandAdapter customAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mEventSelection;
private String[] mProfileSelection;
private int selectedPosition;
List<SampleTO> listParent;
HashMap<String, List<String>> listDataChild;
ArrayList<Event> newsFeedList = new ArrayList<Event>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
context = this;
mTitle = mDrawerTitle = getTitle();
navDrawerView = (LinearLayout) findViewById(R.id.navDrawerView);
mEventSelection = getResources().getStringArray(R.array.event_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.nav_left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
listParent = new ArrayList<SampleTO>();
listDataChild = new HashMap<String, List<String>>();
listParent.add(new SampleTO(getString(R.string.eventDrawer),
R.drawable.event));
listDataChild.put(getString(R.string.eventDrawer),
Arrays.asList(mEventSelection));
customAdapter = new CustomExpandAdapter(this, listParent, listDataChild);
mDrawerList.setAdapter(customAdapter);
mDrawerList.setChoiceMode(ExpandableListView.CHOICE_MODE_SINGLE);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
// Navigation drawer with sub menu goes here
public void selectItem(int groupPosition, int position) {
selectedPosition = position;
mDrawerLayout.closeDrawer(navDrawerView);
if (groupPosition == 0) {
switch (selectedPosition) {
case 0:
break;
case 1:
break;
}
// Navigation item for event
else if (groupPosition == 3) {
switch (selectedPosition) {
case 0:
Intent eventMain = new Intent(context, EventMain.class);
context.startActivity(eventMain);
break;
case 1:
Toast.makeText(NavigationDrawer.this, "Analyze Event",
Toast.LENGTH_LONG).show();
break;
}
}
setTitle(mEventSelection[selectedPosition]);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public void onResume() {
super.onResume();
mDrawerList.setOnGroupClickListener(new OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView
.getPackedPositionForGroup(groupPosition));
parent.setItemChecked(index, true);
String parentTitle = ((SampleTO) customAdapter
.getGroup(groupPosition)).getTitle();
if (parentTitle.equals(getString(R.string.amenityDrawer))) {
Toast.makeText(NavigationDrawer.this, "Amenity",
Toast.LENGTH_LONG).show();
setTitle(parentTitle);
mDrawerLayout.closeDrawer(navDrawerView);
}
return false;
}
});
mDrawerList.setOnChildClickListener(new OnChildClickListener() {
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView
.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
selectItem(groupPosition, childPosition);
return false;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(navDrawerView);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
And then I navigate to my second class which is EventMain.java when the sub item from navigation drawer is selected:
public class EventMain extends NavigationDrawer {
public static MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
LocationManager locationManager;
public static GraphicsLayer graphicsLayer = null;
public static Callout callout;
private int mYear, mMonth, mDay, mHour, mMinute;
private Calendar c;
static final int DATE_DIALOG_ID = 1;
static final int TIME_DIALOG_ID = 2;
private LinearLayout legendDiv, llNewsFeed, llSearch;
private ListView listview;
private Button btnNewsFeed, btnSearchAddr, btnLegends;
private EditText searchAddrET;
private ImageView ivEventGuide;
public static LinearLayout directionDiv;
public static TextView tvDirection, tvDirectionTitle, tvSearchTitle;
static EventController eventCtrl = new EventController();
static Event eventModel = new Event();
private ListAdapter mAdapter;
ArrayList<Event> newsFeedList = new ArrayList<Event>();
#Override
public void onCreate(Bundle savedInstanceState) {
ArcGISRuntime.setClientId("UkIVSWzquykoxCMG");
super.onCreate(savedInstanceState);
setContentView(R.layout.event_main);
context = this;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.event_main, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
It did shows the navigation drawer icon at the EventMain.java. However, when I try to expand it, it does not work. Any ideas?
Thanks in advance.
The xml layout of my EventMain:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/event_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.esri.android.map.MapView
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
initExtent="21801.3, 25801.0, 33218.7, 44830.0" >
</com.esri.android.map.MapView>
//Other linear and relative layouts
</FrameLayout>
</LinearLayout>
In EventMain's onCreate() method, setContentView() is being called after the call to the super.onCreate() method. This is causing the DrawerLayout set in the base class, NavigationDrawer, to be replaced, effectively removing the Drawer. To prevent this, we ensure the DrawerLayout has the standard container FrameLayout for main content, and inflate EventMain's layout into that.
The base Activity's layout, main.xml:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/event_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
...
</android.support.v4.widget.DrawerLayout>
And in the Activity subclass, EventMain:
#Override
public void onCreate(Bundle savedInstanceState) {
...
super.onCreate(savedInstanceState);
ViewGroup content = (ViewGroup) findViewById(R.id.event_frame);
getLayoutInflater().inflate(R.layout.event_main, content, true);
...
}