In MainActivity, I've created a DrawerLayout and ActionBar. Is there any way to use that same Drawer and ActionBar in other activities without writing the same code again? Here's the code I'm using:
Main.xml:
<androidx.drawerlayout.widget.DrawerLayout 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:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:titleTextColor="#FFF"></androidx.appcompat.widget.Toolbar>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary"
>
</androidx.constraintlayout.widget.ConstraintLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/homepage_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
></androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/main_nav"
android:layout_width="277dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu"></com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Main Java (I've Removed The Extra Code [Non Drawer-Actionbar Code]):
DrawerLayout drawerLayout;
Toolbar toolbar;
TextView json;
RequestQueue requestQueue;
ActionBarDrawerToggle actionBarDrawerToggle;
private RequestQueue mqueue;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mqueue = Volley.newRequestQueue(this);
setuptools();
setUpToolbar();
}
private void setUpToolbar()
{
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name) ;
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
toolbar.setNavigationIcon(R.drawable.ic_menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.right_menu,menu);
final MenuItem awesomeMenuItem = menu.findItem(R.id.notification_iconmain);
View awesomeActionView = awesomeMenuItem.getActionView();
awesomeActionView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onOptionsItemSelected(awesomeMenuItem);
}
});
final TextView not_num = (TextView) menu.findItem(R.id.notification_iconmain).getActionView().findViewById(R.id.hotlist_hot);
String username = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String server_url = "https://google.com/api/notifications.php?username="+username;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, server_url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject notification_numbers = jsonArray.getJSONObject(i);
String final_num = notification_numbers.getString("notifications");
if(final_num.equals("0")){
}else{
not_num.setVisibility(View.VISIBLE);
not_num.setText(final_num);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
mqueue.add(request);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.notification_iconmain){
Intent intent_noti = new Intent(this, NotificationsPage.class);
this.startActivity(intent_noti);
}
if(id == R.id.user_icon){
Intent intent_user = new Intent(this, Profile_Page.class);
this.startActivity(intent_user);
}
return super.onOptionsItemSelected(item);
}
}
What It Does:
It creates a slider drawer, an action bar with the right side menu, and displays the notification count on Bell Icon, and each item has its custom on-click event.
Now, how I can use the same drawer, action bar without writing the code again and again in each activity.
Related
I have three Fragments that I am trying to display by clicking the appropriate option from a Navigation Drawer. I have the Navigation Drawer displaying and opening/closing fine. But I can't get any of the Fragments to display in the Activity. The main screen just stays blank whenever I click an option. There are no compilation errors. I am new to Android development and also Java dev, and I've been trying to complete this project for a month so it will be finished as soon as I can get this to work. You may see some instances of redundant code, because I just wanted to try anything that could work and I am not sure what to delete, so any clarification on that would help too.
The Fragments should be displayed as results in a RecyclerView.
MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nView;
private ActionBarDrawerToggle toggle;
private RequestQueue queue;
private List<ATM> atmList;
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find drawer layout
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Find drawer view
nView = (NavigationView) findViewById(R.id.nav_view);
// Set up drawer view
setupDrawerContent(nView);
// Not sure what this does
nView.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(
this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
// Tie DrawerLayout events to the ActionBarDrawerToggle
mDrawer.addDrawerListener(toggle);
queue = Volley.newRequestQueue(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
toggle.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// 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 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.
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
if (toggle.onOptionsItemSelected(item)) {
return true;
}
/* int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}*/
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_items_catalog) {
// Handle the items catalog action
} else if (id == R.id.nav_items_search) {
} else if (id == R.id.nav_atms) {
/*
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
// atmView = findViewById(R.id.atmRecyclerView);
// atmView.setHasFixedSize(true);
// atmView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(MainActivity.this, atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
*/
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
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) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch(menuItem.getItemId()) {
case R.id.nav_items_catalog:
fragmentClass = ShowItems.class;
// TODO: Find out how to show the fragments in these calls
// fragment.listItems(???);
break;
case R.id.nav_items_search:
fragmentClass = SearchItems.class;
break;
case R.id.nav_atms:
fragmentClass = ShowATMs.class;
/*
atmView = findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(this));
*/
break;
default:
fragmentClass = ShowItems.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
mDrawer.closeDrawers();
}
}
ShowATMs method - Want to show a list of ATM Objects in a RecyclerView format:
public class ShowATMs extends Fragment {
private RecyclerView atmView;
private AtmRecyclerViewAdapter atmRecyclerViewAdapter;
private RequestQueue queue;
// TODO: NEED TO CREATE A VIEW THAT WILL INFLATE CORRECT LAYOUT HERE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Is this line needed?
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.atm_view, container, false);
atmView = rootView.findViewById(R.id.atmRecyclerView);
atmView.setHasFixedSize(true);
atmView.setLayoutManager(new LinearLayoutManager(getContext()));
final List<ATM> atmList = new ArrayList<>();
queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, Constants.atmURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject atmObj = response.getJSONObject(i);
ATM atm = new ATM();
atm.setAtmId(atmObj.getString("atmid"));
atm.setTitle(atmObj.getString("title"));
atm.setAddress(atmObj.getString("address"));
atm.setType(atmObj.getString("type"));
atm.setLat(atmObj.getDouble("lat"));
atm.setLon(atmObj.getDouble("lon"));
atm.setOnlineStatus(atmObj.getString("onlineStatus"));
atmList.add(atm);
// Log.d("ATM Statuses", atmList.get(i).getOnlineStatus());
}
atmRecyclerViewAdapter = new AtmRecyclerViewAdapter
(getContext(), atmList);
atmView.setAdapter(atmRecyclerViewAdapter);
atmRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
return rootView;
}
}
XML Files
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment android:name="com.camelr.bilal.camelrecommerceproject.Fragments.ShowATMs"
android:id="#+id/ATMs"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout="#layout/atm_view" />
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!--<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />-->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/colorPrimary"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
atm_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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=".MainActivity"
tools:showIn="#layout/activity_main">
-->
<android.support.v7.widget.RecyclerView
android:id="#+id/atmRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
I have two other Fragments that I set up a little differently but just showing the one for ATMs because I feel it is the closest to working.
I have implemented a drawer layout whereby when I click a navigation view item a tab layout opens up. The tablayout comes in fine but the problem is when i click the back button of the tab layout the application crashes with No drawer view found with gravity LEFT. Also I have noticed that there is a bit of a lag when the navigation drawer closes when the tab layout comes in, the drawer does not close smoothly.
Below is my java code and xml:
public class Navigation extends AppCompatActivity implements
ItemFragment.OnHeadlineSelectedListener,
SortFragment.OnHeadlineSelectedListener{
private static final String TAG = Navigation.class.getSimpleName();
Toolbar toolbar;
FragmentManager mFragmentManager;
private TextView mCounter;
private ImageView cart;
FragmentTransaction mFragmentTransaction;
public int id, tabPosition = 0, tabPositionNavigation = 0;
private String drinkToSort = "empty";
SharedPreferences preferences;
private LocalStore localStore;
private String userName, email, location;
private String phone;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation);
localStore = new LocalStore(this);
id = localStore.getLoggedInUser().getId();
userName = localStore.getLoggedInUser().getUserName();
email = localStore.getLoggedInUser().getEmail();
phone = localStore.getLoggedInUser().getPhone();
Log.i(TAG,"USERDATA" + "[" + id + userName + email + phone + location + "]");
relativeLayout = (RelativeLayout) findViewById(R.id.main_content);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle("hello");
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("hello");
}
};
Bundle extras = getIntent().getExtras();
if (extras != null) {
this.tabPosition = extras.getInt("tabPosition");
this.tabPositionNavigation = extras.getInt("tabPositionNavigation");
this.drinkToSort = extras.getString("drinkToSort");
Log.d(TAG, tabPosition + tabPositionNavigation + drinkToSort);
}
Bundle bundle = new Bundle();
bundle.putString("drinkToSort", drinkToSort);
LiquorFragment obj = new LiquorFragment();
obj.setArguments(bundle);
int width = getResources().getDisplayMetrics().widthPixels/2;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new NavigationFragment()).commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.details_activity, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.cart_no).getActionView();
mCounter = (TextView) badgeLayout.findViewById(R.id.counter);
Log.d("sameSelectionCount", CartCounter.getCounter()+"");
mCounter.setText(""+CartCounter.getCounter());
cart = (ImageView) badgeLayout.findViewById(R.id.cart);
cart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("cart_no","cart_no");
Intent intent = new Intent(getApplicationContext(), ShoppingList.class);
startActivity(intent);
}
});
return true;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume() {
super.onResume();
//TabFragment.viewPager.setCurrentItem(1);
Log.d("landposzq",tabPositionNavigation + "");
if (tabPositionNavigation != 0){
if (tabPositionNavigation == 1){
NavigationFragment.viewPager.setCurrentItem(0);
} else if (tabPositionNavigation == 2){
NavigationFragment.viewPager.setCurrentItem(1);
} else if (tabPositionNavigation == 3){
NavigationFragment.viewPager.setCurrentItem(2);
} else if (tabPositionNavigation == 4){
NavigationFragment.viewPager.setCurrentItem(3);
} else if (tabPositionNavigation == 5){
NavigationFragment.viewPager.setCurrentItem(4);
}
}
}
}
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:openDrawer="start"
android:fitsSystemWindows="true">
<!--Main content-->
<RelativeLayout
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/qb"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar" />
</RelativeLayout>
<!--Navigation Drawer-->
<android.support.design.widget.NavigationView
android:id="#+id/main_drawer"
android:layout_width="290dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#color/white"
app:headerLayout="#layout/drawer_header"
app:itemTextColor="#000000"
app:itemIconTint="#color/qb"
app:menu="#menu/menu_drawer" >
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="20dp"
android:src="#drawable/balloon4"
/>
<TextView
android:id="#+id/free_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffff99"
android:gravity="center_vertical"
android:padding="10dp"
android:drawableRight="#drawable/direction"
android:height="60dp"
android:textSize="18sp"
android:text="GET FREE DRINKS"
android:textColor="#000000"
android:layout_gravity="bottom"
/>
</LinearLayout>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Change your onBackPressed() method as below :
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
I want use NavidationDrawer for application menu, but when click on NavigationItems not action! I want when click on NavigationItems, start other Activities.
Main XML :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout 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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/backgroundPrimary"
tools:context="com.tellfa.dastanak.Activities.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/main_appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|snap"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.tellfa.dastanak.Components.CodeSaz_TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:singleLine="true"
android:textColor="#color/textLight"
android:textSize="25sp" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/main_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/tabIndicatorColor" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/main_viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/menu_header"
app:itemIconTint="#color/colorPrimary"
app:itemTextColor="#color/colorPrimary"
app:menu="#menu/menu_main_page" />
</android.support.v4.widget.DrawerLayout>
Main code :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar toolbar;
private DrawerLayout mDrawerLayout;
private ViewPager viewPager;
private TabLayout tabLayout;
private DataBase dataBase;
private Cat1_frag_AsyncTask task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBase = new DataBase(this);
try {
dataBase.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
TextView toolbar_text = (TextView) findViewById(R.id.toolbar_title);
toolbar_text.setText(R.string.app_name_fa);
final ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("");
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_driver);
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
viewPager = (ViewPager) findViewById(R.id.main_viewPager);
if (viewPager != null) {
setupViewPager(viewPager);
}
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
if (tabLayout != null) {
tabLayout.setupWithViewPager(viewPager);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
case R.id.action_recyclerView:
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_recyclerView:
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
}
return onNavigationItemSelected(item);
}
private void setupViewPager(ViewPager viewPager) {
Main_frag_adapter mainFragAdapter = new Main_frag_adapter(getSupportFragmentManager());
mainFragAdapter.addFragment(new Cat1_fragment_recycler(), "آموزنده");
mainFragAdapter.addFragment(new Cat2_fragment_recycler(), "عاشقانه");
mainFragAdapter.addFragment(new Cat3_fragment_recycler(), "بزرگان");
mainFragAdapter.addFragment(new Cat4_fragment_recycler(), "متفرقه");
viewPager.setAdapter(mainFragAdapter);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private void forceRTLIfSupported() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
}
How can i it? tnx <3
put this line
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
in
private void setupDrawerContent(NavigationView navigationView)
so updated method is like:
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
startActivity(new Intent(getApplicationContext(), Recycler_Page.class));
mDrawerLayout.closeDrawers();
return true;
}
});
}
I followed a tutorial to push facebook info from login into an activity with a navigation, then put the into on top, as shown, which, after days of altering code, I finally got it to work.
But now I cant get the original header to go away. I've tried changing every part of the code, but I always end up with all or nothing. I know two heads are better than one, but this is an exception to the rule.
Also, I guess I cant post images, so, the original header is on top, where it should be.
The new header with my facebook profile picture and info, is underneath that.
And below that, starts the navigation drawer menu.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email, tokens;
ImageView user_picture;
NavigationView navigation_view;
String name;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tokens = (TextView)findViewById(R.id.textView17);
button2 = (Button)findViewById(R.id.button2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
final String uid = intent.getStringExtra("Uid");
setNavigationHeader(); // call setNavigationHeader Method.
setUserProfile(jsondata, uid);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setVisibility(View.INVISIBLE);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Tokens token = new Tokens("100");
ref.setValue(token);
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Toast.makeText(getApplicationContext(), uid, Toast.LENGTH_LONG).show();
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
updateText();
}
});
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Firebase tokRef = ref.child("tokens");
//tokRef.setValue(mAuthData.getProvider());
//Tokens token = new Tokens(100);
//ref.setValue(token);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("tokens").getValue() != null) {
name = (String) dataSnapshot.child("tokens").getValue().toString();
tokens.setText(name);
//tokens.setText(dataSnapshot.getValue().toString());
// Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
// System.out.println(dataSnapshot.getValue());
// String woot = dataSnapshot.getValue().toString();
// tokens.setText(woot);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();
}
});
}
public void updateText(){
Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
Firebase tokRef = ref.child("tokens");
//tokRef.setValue(mAuthData.getProvider());
// Tokens token = new Tokens(100);
// ref.setValue(token);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot tokenSnapshot: dataSnapshot.getChildren()){
Tokens token = tokenSnapshot.getValue(Tokens.class);
System.out.println(token.toString());
name = token.toString();
// name = (String) dataSnapshot.child("tokens").getValue();
tokens.setText(name);
}
// name = (String) dataSnapshot.child("tokens").getValue().toString();
// tokens.setText(name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();
}
});
}
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
navigation_view.removeHeaderView(null);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
user_name = (TextView) header.findViewById(R.id.username);
user_picture = (ImageView) header.findViewById(R.id.profile_pic);
user_email = (TextView) header.findViewById(R.id.email);
}
public void setUserProfile(String jsondata, String uid){
try
{
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
// user_email.setText(MainActivity.uEmail);
user_name.setText(response.get("name").toString());
// user_name.setText(MainActivity.uName);
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url")).into(user_picture);
}
catch
(Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_slots) {
// Handle the camera action1
Intent intent2 = new Intent(this, SlotPageView.class);
startActivity(intent2);
} else if (id == R.id.nav_spin) {
Intent intent2 = new Intent(this, DailySpinActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_offers) {
} else if (id == R.id.nav_prizes) {
Intent intent2 = new Intent(this, PrizesActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_winners) {
Intent intent2 = new Intent(this, WinnersActivity.class);
startActivity(intent2);
} else if (id == R.id.nav_stats) {
} else if (id == R.id.nav_account) {
Intent intent2 = new Intent(this, AccountActivity.class);
startActivity(intent2);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
android:fitsSystemWindows="true" tools:openDrawer="start">
<include layout="#layout/app_bar_home" android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home" app:menu="#menu/activity_home_drawer" />
App bar home xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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" android:fitsSystemWindows="true"
tools:context="learn2crack.learn2crackfb.HomeActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<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/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_home" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Nav header home xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="#dimen/nav_header_height"
android:background="#drawable/side_nav_bar"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:theme="#style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_pic"
android:layout_width="80dp"
android:layout_height="80dp"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:src="#android:drawable/sym_def_app_icon"
/>
<TextView android:id="#+id/username"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:paddingTop="#dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textSize="14dp"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textColor="#000000" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="android.studio#android.com" />
</LinearLayout>
u have to pass the header view into
navigation_view.removeHeaderView(navigation_view.getHeaderView(0);
and not null
navigation_view.removeHeaderView(null);
when you add header using app:headerLayout="#layout/nav_header_home" just like below
<android.support.design.widget.NavigationView android:id="#+id/nav_view"
android:layout_width="wrap_content" android:layout_height="match_parent"
android:layout_gravity="start" android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home" app:menu="#menu/activity_home_drawer" />
then no need to add header again from code
remove below lines from setNavigationHeader() method
navigation_view.removeHeaderView(null);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);
after remove method look like below
Edit /
public void setNavigationHeader(){
navigation_view = (NavigationView) findViewById(R.id.nav_view);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
user_name = (TextView) navigation_view.findViewById(R.id.username);
user_picture = (ImageView) navigation_view.findViewById(R.id.profile_pic);
user_email = (TextView) navigation_view. findViewById(R.id.email);
}
Try this, It's workable and tested.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.removeHeaderView(navigationView.getHeaderView(0));
View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView user_dp = headerLayout.findViewById(R.id.user_dp);
TextView user_fullname = headerLayout.findViewById(R.id.user_fullname);
TextView user_email = headerLayout.findViewById(R.id.user_email);
user_dp.setBackgroundResource(R.drawable.user);
user_fullname.setText(fullName);
user_email.setText(uemail);
}
I have an activity which has a coordinator layout with viewpager and CircularPager Indicator. I am trying to use MaterialRefreshLayout Library to do pull to refresh
The library can be found at Pull to refresh library
However, after I use pull to refresh my data, the viewpager just doesn't update the rest of the fragment and hence it dosn't scroll. Once I do background foreground it scrolls alright. Below is the Layout and activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="myPackage.HomeActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<com.cjj.MaterialRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:overlay="true"
app:progress_show_arrow="true"
app:wave_show="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginTop="65dp"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="#dimen/viewpager_height_none"
android:layout_weight="1"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<mypackage.ui.CirclePageIndicator
android:id="#+id/indicator"
style="#style/PageIndicator"
android:clickable="false"
app:fillColor="#color/default_circle_indicator_stroke_color"
app:pageColor="#color/circlepageindicator_fill_color"
app:radius="#dimen/circlepageindicator_radius" />
</LinearLayout>
</com.cjj.MaterialRefreshLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
And Below is the Activity
public class HomeActivity extends AppCompatActivity {
private SectionPagerAdapter mSectionPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private CirclePageIndicator mPagerCountIndicator;
private MaterialRefreshLayout materialRefreshLayout;
private Integer mTaskCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Bundle extras = getIntent().getExtras();
if(extras != null) {
mTaskCount= extras.getInt("task_Count");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
updateandShowViewPager();
materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
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();
}
});
}
#Override
protected void onResume() {
super.onResume();
materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
#Override
public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
refresh();
}
});
materialRefreshLayout.finishRefresh();
}
#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_home, 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);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
private void startMyAsyncTask(AsyncTask asyncTask){
//execute my AsyncTask and call Update and Show ViewPager
}
private void updateandShowViewPager(){
AsyncTaskCallBack asyncTaskCallBack = new AsyncTaskCallBack() {
#Override
public void onSuccess() {
displayViewPager();
}
}
};
for(int taskCount = 1; taskCount <= mTaskCount; taskCount ++){
myAsyncTask = new MyAsyncTask();
startMyAsyncTask(myAsyncTask );
}
}
private void displayViewPager(){
mSectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionPagerAdapter);
mTaskCountIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
mTaskCountIndicator .setViewPager(mViewPager);
}
private void refresh() {
MyAsyncTask myAsyncTask = null;
MyAsyncTaskCallBack myAsyncTaskCallBack = new MyAsyncTaskCallBack () {
#Override
public void onSuccess() {
updateViewPager();
}
}
};
for(int taskCount = 1; taskCount <= mTaskCount; taskCount ++){
myAsyncTask = new MyAsyncTask();
startMyAsyncTask(myAsyncTask );
}
}
private void updateViewPager(){
mSectionPagerAdapter.setPagerItem(myMap);
mSectionPagerAdapter.notifyDataSetChanged();
mCartCountIndicator.notifyDataSetChanged();
mViewPager.invalidate();
}
}
Not Sure what am I doing wrong here. Appreciate any suggestion.
use
mViewPager.setOffscreenPageLimit(numberOfPages);
Okay, figured since it is the activity that is not being refreshed itself I tried this.onResume() in the refresh method once I do notifyDataSetChanged(). It works.
Not sure it is the cleanest solution though