Pull refresh with recycle view doesn't work - java

When I move the screen of my device under to refresh rss news feed, it doesn't work. i tried to refresh news with swiperefreshlayout. I don't know why but it doesn't work:
MAIN ACTIVITY:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
SwipeRefreshLayout refreshLayout;
private LinearLayoutManager linearLayoutManager;
private MyAdapter myRecyclerViewAdapter;
Context context;
ArrayList<FeedItem> feedItems=new ArrayList<FeedItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
refreshLayout=(SwipeRefreshLayout)findViewById(R.id.swipeLayout);
refreshLayout.setOnRefreshListener((SwipeRefreshLayout.OnRefreshListener) context);
refreshLayout.setColorSchemeColors(0, 0, 0, 0);
refreshLayout.setProgressBackgroundColor(android.R.color.transparent);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
ReadRss readRss=new ReadRss(this,recyclerView);
readRss.execute();
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int topRowVerticalPosition =
(recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
refreshLayout.setEnabled(topRowVerticalPosition >= 0);
refreshLayout.setEnabled(linearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
}
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
});
/*recyclerView= (RecyclerView) findViewById(R.id.recyclerview);
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
myRecyclerViewAdapter = new MyAdapter(context,feedItems);
//myRecyclerViewAdapter.setOnItemClickListener(this);
recyclerView.setAdapter(myRecyclerViewAdapter);
recyclerView.setLayoutManager(linearLayoutManager);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
CONTENT MAIN.XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.rssreader.MainActivity"
tools:showIn="#layout/activity_main">
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

You have defined setOnRefreshListener in your refreshLayout but didn't implemented it.
you have to use setOnRefreshListener method on your swipe refresh layout like this.
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// call your Refresh method here
mswipeRefreshLayout.setRefreshing(false);
}
});

You have to set OnRefreshListener to the SwipeRefreshListener and handle the refresh in the callback.
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
#Override
public void onRefresh()
{
// handle your refresh logic
}
});

Related

Recyclerview in fragment not displaying alert dialog result right away

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.

all fragments are loading at time of activity

I am very...very new to android development and I am trying to recreate a hybrid app I built in ionic, but do it in actual android.
I am having an issue with either layouts or fragment loading that I can't figure out.
What I want is something similar to the IG layout, where there is a bar at the bottom for navigation, clicking the button would load the new page. From my understanding the best way to accomplish that is to use a main activity, then each of the tabs at the bottom are fragments.
So I built that, but I want the top toolbar to disappear on the second tab, so in the second tab "onCreateView" method I added the toolbar.setVisibility(View.GONE); however, as soon as I load the app, even on the first tab, the toolbar at the top is gone, signifying it is loading the views for each fragment when the app loads. I would think that would severely impact performance on a large app. Am I crazy?
Here is my main layout for the main activity...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.view.ViewPager
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabSelectedTextColor="#FFFFFF"
app:tabTextColor="#D3D3D3"
app:tabIndicatorColor="#FF00FF"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Then my HomeActivity class..
public class HomeActivity extends BaseActivity implements OnFragmentTouched {
private TextView mTextMessage;
private static final String SELECTED_ITEM = "arg_selected_item";
private int mSelectedItem;
private BottomNavigationView mBottomNav;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ViewPager pager = (ViewPager) findViewById(R.id.content);
PagerAdapter pagerAdapter = (PagerAdapter) new PagerAdapter(getSupportFragmentManager(), HomeActivity.this);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(pager);
for(int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
switch(item.getItemId()) {
case R.id.navigation_home:
frag = new AllPostsFragment();
break;
case R.id.navigation_dashboard:
frag = ProfileFragment.newInstance(user.getUid());
break;
case R.id.navigation_notifications:
frag = new ChatListFragment();
break;
}
mSelectedItem = item.getItemId();
}
#VisibleForTesting
public ProgressDialog mProgressDialog;
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onStop() {
super.onStop();
hideProgressDialog();
}
#Override
public void onFragmentTouched(Fragment fragment, float x, float y) {
Log.d("FRAGMENT_TOUCHED", "The ChatListFragment touch happened");
if(fragment instanceof ChatFragment) {
final ChatFragment theFragment = (ChatFragment) fragment;
Animator unreveal = theFragment.prepareUnrevealAnimator(x, y);
unreveal.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
getSupportFragmentManager().beginTransaction().remove(theFragment).commit();
getSupportFragmentManager().executePendingTransactions();
}
#Override
public void onAnimationCancel(Animator animation) {}
#Override
public void onAnimationRepeat(Animator animation) {}
});
unreveal.start();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
private class PagerAdapter extends FragmentPagerAdapter {
Context context;
String tabTitles[] = new String[] {"Home", "Profile", "Chat"};
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return new AllPostsFragment();
case 1: return ProfileFragment.newInstance(user.getUid());
case 2: return new ChatListFragment();
default:
return new AllPostsFragment();
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(HomeActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
So, in the "ProfileFragment" in the onCreateView method I have...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.userPostsRecycler);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setVisibility(View.GONE);
followingCountText = rootView.findViewById(R.id.following_count);
followersCountText = rootView.findViewById(R.id.followers_count);
titleLayout = rootView.findViewById(R.id.toolbar_layout);
titleLayout.setTitle(user.getDisplayName());
fab1Container = rootView.findViewById(R.id.fab_1);
fab2Container = rootView.findViewById(R.id.fab_2);
ImageView profilePhoto = (ImageView) rootView.findViewById(R.id.profile_photo);
Glide.with(this).load(user.getPhotoUrl()).into(profilePhoto);
fabContainer = (LinearLayout) rootView.findViewById(R.id.fabContainerLayout);
fab = (FloatingActionButton) rootView.findViewById(R.id.profile_fab);
instigatingFab = fab;
fabBaseX = fab.getX();
fabBaseY = fab.getY();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBlurredDialog();
}
});
progressDialog = new ProgressDialog(getContext());
uploads = new ArrayList<>();
progressDialog.setMessage("Please wait...");
progressDialog.show();
DatabaseReference followersDB = FirebaseDatabase
.getInstance()
.getReference("followers")
.child(user.getUid())
.child("count");
followersDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followersCount = dataSnapshot.getValue(Integer.class);
followersCountText.setText(Integer.toString(followersCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingReference = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("users");
followingReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingDB = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("count");
followingDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followingCount = dataSnapshot.getValue(Integer.class);
followingCountText.setText(Integer.toString(followingCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference("/userPosts").child(user.getUid()).child("posts");
mDatabase.limitToFirst(25).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String postID = postSnapshot.getKey();
uploads.add(postID);
}
uploads.add("-KtvzkOL_75wiKA4CMsr");
adapter = new ProfileUserPostsViewHolder(getContext(), uploads);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
return rootView;
}
As you can see I am setting the visibility for the toolbar from the HomeActivity to View.GONE, however, the toolbar is gone from all fragments now. I just want a bottom navigation setup with a top toolbar that can be hidden when certain fragments load, but is visible in other fragments. Is that even possible? Thank you.
You can control the numbers of fragments loading in view pager by simply using this method:
viewPager.setOffscreenPageLimit(1); // where n is the number of offscreen pages you want to load.
you can increase or decrease the number of fragments loading according to your requirements but atleast 1.
hope this will help you.

How to add selected players from MyPlayerActivity and add those players into MainActivity Map as markers?

I would like to select few players ( highlighted in purple colors ie Player 1, Player 3 & Player 5) from 'MyPlayerActivity' and add these selected players into a mapbox Map as markers (MainActivity) during on click on 'Add Player' button.
Could someone please help me on how to achieve this ?
Following is my 'MyPlayerActivity' code
public class MyPlayerActivity extends ListActivity {
private static int lastClickId = -1;
// Array of strings storing country names
String[] players = new String[] {
"Player 1",
"Player 2",
"Player 3",
"Player 4",
"Player 5"
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] images = new int[]{
R.drawable.play_1,
R.drawable.play_2,
R.drawable.play_3,
R.drawable.play_4,
R.drawable.play_5
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
final ListView listView = (ListView) findViewById(android.R.id.list);
View headerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
getListView().addHeaderView(headerView);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<6;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("label", "" + players[i]);
hm.put("imgs", Integer.toString(images[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "imgs","label"};
// Ids of views in listview_layout
int[] to = { R.id.imgs,R.id.label};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_view, from, to);
// Getting a reference to listview of main.xml layout file
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
// Getting the Container Layout of the ListView
RelativeLayout relativeLayoutParent = (RelativeLayout) container;
//LinearLayout linearLayoutParent = (LinearLayout) container;
RelativeLayout relativeLayoutChild = (RelativeLayout) relativeLayoutParent.getChildAt(1);
// Getting the inner Linear Layout
// LinearLayout linearLayoutChild = (LinearLayout ) linearLayoutParent.getChildAt(1);
// Getting the Player TextView
TextView myPlayer = (TextView) relativeLayoutChild.getChildAt(0);
Toast.makeText(getBaseContext(), myPlayer.getText().toString(), Toast.LENGTH_SHORT).show();
}
};
// Setting the item click listener for the listview
listView.setOnItemClickListener(itemClickListener);
}
}
Following is the list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imgs"
android:layout_width="75dp"
android:layout_height="75dp"
android:paddingTop="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:text="#+id/label"
android:textSize="17sp" >
</TextView>
<Button
android:id="#+id/button2"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="10dp"
android:text="#string/Add_Player"
android:background="#66ccff"
android:textColor="#ffffff">
</Button>
<ListView android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Below is the 'MainActivity' code, where I have initialized my map and this is where I would need to add my Player markers and display in mapbox map.
'MainActivity' code where I have initialized my map:
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private MapView mapView;
private MapboxMap map;
private Marker customMarker;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapboxAccountManager.start(this, "token");
final boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
setContentView(R.layout.activity_main);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
onMapReady(map);
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
Log.i("MapAsync", " is called");
//you need to initialize 'map' with 'mapboxMap';
map = mapboxMap;
//map.setOnMapLongClickListener(new LatLng);
map.setOnMapLongClickListener(new MapboxMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(#NonNull LatLng point) {
if (customMarker != null) {
// Remove previous added marker
map.removeAnnotation(customMarker);
customMarker = null;
}
customMarker = map.addMarker(new MarkerOptions()
.title("Custom Marker")
.snippet(new DecimalFormat("#.#####").format(point.getLatitude()) + ", "
+ new DecimalFormat("#.#####").format(point.getLongitude()))
.position(point));
}
}); // Long click Ends here
}
});
}
// Initialize the onMapReady
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.map = mapboxMap;
}
private void addDrawerItems() {
String[] osArray = { "Map", "Players", "Video", "TestPlayer", "My Profile"};
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// depending on the position in your drawer list change this
switch (position) {
case 0: {
Toast.makeText(MainActivity.this, "Access map", Toast.LENGTH_SHORT).show();
break;
}
case 1:{
Intent intent = new Intent(MainActivity.this, ListPlayerActivity.class);
startActivity(intent);
Toast.makeText(MainActivity.this, "See players arena", Toast.LENGTH_SHORT).show();
break;
}
case 2:{
Intent appIntent = new Intent(MainActivity.this, PlayYoutubeActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "See Video", Toast.LENGTH_SHORT).show();
break;
}
case 3:{
Intent appIntent = new Intent(MainActivity.this, MyPlayerActivity.class);
startActivity(appIntent);
Toast.makeText(MainActivity.this, "Test to see my players", Toast.LENGTH_SHORT).show();
break;
}
default:
break;
}
Toast.makeText(MainActivity.this, "More details to follow", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public class TelemetryServiceNotConfiguredException extends RuntimeException {
public TelemetryServiceNotConfiguredException() {
super("\nTelemetryService is not configured in your applications AndroidManifest.xml. " +
"\nPlease add \"com.mapbox.mapboxsdk.telemetry.TelemetryService\" service in your applications AndroidManifest.xml" +
"\nFor an example visit For more information visit https://www.mapbox.com/android-sdk/.");
}
}
}
To add a marker to the map you can use this snippet:
mapboxMap.addMarker(new MarkerViewOptions()
.position(new LatLng(<position of player>)));
If the listview and map are in separate activities, you can pass the selected player information to the map activity using an intent. Is this what you were looking for?

Hide a Floating Action Button of another Layout

I have a FloatingActionButton inside of may activity_main.xml layout which is named fabBtn.
My application is built with a ViewPager and three Fragments.I want to hide the FloatingActionButton when my first Fragment detects a scroll, but I keep getting a NullPointerException if the user starts scrolling.
I believe it could be that my fragment can't get the FloatingActionButton from the activity_main.xml layout?
Here is my activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="lh.com.newme.MainActivity"
xmlns:fab="http://schemas.android.com/tools">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|snap"/>
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabMode="fixed"
app:layout_scrollFlags="snap|enterAlways"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#ffffff" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabBtn"
android:layout_marginBottom="#dimen/codelab_fab_margin_bottom"
android:layout_marginRight="#dimen/codelab_fab_margin_right"
android:layout_width="wrap_content"
fab:fab_type="normal"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
app:backgroundTint="#color/fab_ripple_color"
android:src="#drawable/ic_plus"
app:fabSize="normal"
/>
</android.support.design.widget.CoordinatorLayout>
Here is my first Fragment from where I want to hide the FloatingActionButton:
public class Ernaehrung extends Fragment {
NestedScrollView nsv;
FloatingActionButton fab;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
final View rootView = inflater.inflate(R.layout.ernaehrung, container, false);
Button Fruehstuck = (Button) rootView.findViewById(R.id.fruehstuck);
Button Mittagessen = (Button) rootView.findViewById(R.id.mittagessen);
Button Snacks = (Button) rootView.findViewById(R.id.snacks);
Fruehstuck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent FruehstuckScreen = new Intent(getActivity(), lh.com.newme.Fruehstuck.class);
startActivity(FruehstuckScreen);
}
});
Mittagessen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent MittagScreen = new Intent(getActivity(), lh.com.newme.Mittagessen.class);
startActivity(MittagScreen);
}
});
Snacks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent SnackScreen = new Intent(getActivity(), lh.com.newme.Snacks.class);
startActivity(SnackScreen);
}
});
nsv = (NestedScrollView)rootView.findViewById(R.id.Nsv);
fab = (FloatingActionButton)rootView.findViewById(R.id.fabBtn);
nsv.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
#Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
if (oldScrollY < scrollY){
fab.hide();
}
else
fab.show();}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.main_menu_ernaehrung, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
int id = item.getItemId();
if (id == R.id.benutzer){
}
return super.onOptionsItemSelected(item);
}
}
This is my MainActivity.class :
public class MainActivity extends AppCompatActivity {
FloatingActionButton fabBtn;
CoordinatorLayout rootLayout;
Toolbar toolbar;
TabLayout tabLayout;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(2);
// Give the TabLayout the ViewPager
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
fab.show();
...
break;
case 1:
fab.show();
...
break;
case 2:
fab.hide();
break;
default:
fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
initInstances();
}
private void initInstances() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
rootLayout = (CoordinatorLayout) findViewById(R.id.rootLayout);
fabBtn = (FloatingActionButton) findViewById(R.id.fabBtn);
}
#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_edit, 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.einstellungen) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
First of all, change your line
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fabBtn);
to
fabBtn = (FloatingActionButton)findViewById(R.id.fabBtn);
Solution #1 - get view (if you need object)
Then, in your MainActivity add getter for your FloatingActionButton, like
public FloatingActionButton getFloatingActionButton {
return fabBtn;
}
Finally, in your Fragment call:
FloatingActionButton floatingActionButton = ((MainActivity) getActivity()).getFloatingActionButton();
and
if (floatingActionButton != null) {
floatingActionButton.hide();
}
or
if (floatingActionButton != null) {
floatingActionButton.show();
}
Solution #2 - add two methods in MainActivity (if you need only specific methods, like show() / hide())
public void showFloatingActionButton() {
fabBtn.show();
};
public void hideFloatingActionButton() {
fabBtn.hide();
};
And in your Fragment call to hide:
((MainActivity) getActivity()).hideFloatingActionButton();
or to show:
((MainActivity) getActivity()).showFloatingActionButton();
Note
If you use more than one Activity, you must check if it's proper Activity:
if (getActivity() instanceof MainActivity) {
getActivity().yourMethod(); // your method here
}
In your fragment your rootView layout is not main layout and you cannot expect the rootView will return the fab button. Thats why you are getting null pointer exception
You better use interface to detect page scrolling and controll it via your activity

Navigation Drawer for Multiple Activity

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

Categories