I have a view pager in Activity_Homescreen and is set to a FragmentPagerAdapter. The activity has 4 tabs and the pager adapter uses the same fragment for first three tabs and another fragment for the the last tab in the tab layout.The fragment for initial 3 tabs have two fragments (map and recycler view) nested inside that fragment.
Initially when i use the app the fragments are being loaded correctly ,ie, when i go from TAB 1-->TAB 2-->Tab 3.
But when i go back to Tab 2 the map fragment will not display any markers .The google map and recycler view are loaded correctly but only markers are not visible..On debugging, I realized that the fragment is being loaded twice.Same condition occurs after going from TAB 4 to TAB 3.
It would be great if some one could post a solution as soon as possible.Thanks in advance.
Activity_Homescreen.java
private Toolbar toolbar;
private DrawerLayout drawerLayout;
private TabLayout tabLayout;
private SearchView searchView;
private boolean searchSubmitted = false;
private NetworkInfo activeNetworkInfo;
private Homescreen_Pojo pojoInstance = Homescreen_Pojo.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
pojoInstance.setActiveNetworkInfo(activeNetworkInfo);
pojoInstance.setAdvancedSearchSubmitted(false);
pojoInstance.setSearchSubmitted(false);
setupToolbar();
setupTabLayout();
setupNavigationDrawer();
setupNavigationItems();
setupViewPager();
}
#Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
}
public void setupToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toolbar.setLogo(R.drawable.header_logo);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
private void setupNavigationDrawer() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
drawerLayout.setDrawerListener(drawerToggle);
drawerToggle.syncState();
}
private void setupNavigationItems() {
final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
TextView userNameCtrl = (TextView) navigationView.findViewById(R.id.navigation_userName);
ImageView userImageCtrl = (ImageView) navigationView.findViewById(R.id.navigation_userImage);
String userName = UserCredentials.getInstance().getUserName();
String userPhotoUrl = UserCredentials.getInstance().getUserPhotoUrl();
if (userName != null && userPhotoUrl != (null)) {
userNameCtrl.setText(userName);
new LoadImage(userImageCtrl).execute(userPhotoUrl);
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
CharSequence menuItemTitle = menuItem.getTitle();
if (Objects.equals(menuItemTitle, "Rate App")) {
final String appPackageName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
} else {
Activity_Login.integration.logout();
Intent intent = new Intent(getApplicationContext(), Activity_Login.class);
startActivity(intent);
}
drawerLayout.closeDrawers();
return true;
}
});
}
private void setupTabLayout() {
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.near_me_hover).setTag(1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.all_hostels).setTag(2));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.top_five).setTag(3));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.advanced_search).setTag(4));
}
private void setupViewPager() {
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(pagerAdapter);
pojoInstance.setViewPager(viewPager);
}
public boolean isInternetConnected() {
boolean connection = true;
activeNetworkInfo = pojoInstance.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
connection = false;
}
return connection;
}
#Override
protected void onResume() {
final ViewPager viewPager = pojoInstance.getViewPager();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
viewPager.setCurrentItem(tab.getPosition());
tab.setIcon(R.drawable.near_me_hover);
break;
case 1:
viewPager.setCurrentItem(tab.getPosition());
tab.setIcon(R.drawable.all_hostels_hover);
break;
case 2:
viewPager.setCurrentItem(tab.getPosition());
tab.setIcon(R.drawable.top_five_hover);
break;
case 3:
viewPager.setCurrentItem(tab.getPosition());
tab.setIcon(R.drawable.advanced_search_hover);
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
switch (tab.getPosition()) {
case 0:
tab.setIcon(R.drawable.near_me);
break;
case 1:
tab.setIcon(R.drawable.all_hostels);
break;
case 2:
tab.setIcon(R.drawable.top_five);
break;
case 3:
tab.setIcon(R.drawable.advanced_search);
break;
}
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
tabLayout.getTabAt(position).select();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
super.onResume();
}
public void infoClick(MenuItem menuItem) {
AlertDialog.Builder builder = new AlertDialog.Builder(Activity_HomeScreen.this);
LayoutInflater inflater = LayoutInflater.from(getApplication());
View infoView = inflater.inflate(R.layout.homescreen_toolbar_info, null);
builder.setView(infoView);
builder.setCancelable(true);
builder.setIcon(R.drawable.launcher_icon);
builder.setNeutralButton("Ok, got it", null);
builder.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home_screen, menu);
final MenuItem searchItem = menu.findItem(R.id.search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = null;
if (searchItem != null) {
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setSubmitButtonEnabled(false);
searchView.setQueryHint("Place / Hostel Name");
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toolbar.setBackgroundColor(R.drawable.header_searchview);
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
searchView.onActionViewCollapsed();
toolbar.setBackgroundResource(R.drawable.header_bg);
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Homescreen_Pojo.getInstance().setUserQuery(query);
pojoInstance.setSearchSubmitted(true);
Intent intent = new Intent(Activity_HomeScreen.this, Activity_SimpleSearchView.class);
startActivity(intent);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
PagerAdapter.java
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment_Tabs_CommonUI();
case 1:
return new Fragment_Tabs_CommonUI();
case 2:
return new Fragment_Tabs_CommonUI();
case 3:
return new Fragment_Tab4();
}
return null;
}
#Override
public int getCount() {
return 4;
}
}
Fragment for first 3 tabs
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int num = Homescreen_Pojo.getInstance().getViewPager().getCurrentItem();
tabView = inflater.inflate(R.layout.tab_common_ui, container, false);
if (Homescreen_Pojo.getInstance().isSearchSubmitted()) {
setUserVisibleHint(true);
}
return tabView;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
int number = Homescreen_Pojo.getInstance().getViewPager().getCurrentItem();
if (isVisibleToUser) {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
if (status == ConnectionResult.SUCCESS) {
FragmentManager fragmentManager = getChildFragmentManager();
MapFragment mapFragment = new MapFragment();
CardList_Fragment listFragment = new CardList_Fragment();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.map_container, mapFragment);
transaction.add(R.id.cardlist_container, listFragment);
transaction.commitAllowingStateLoss();
fragmentManager.executePendingTransactions();
} else {
Snackbar.make(tabView, "GooglePlay Service not available !!", Snackbar.LENGTH_LONG).show();
}
}
}
}
MapFragment
public MapFragment() {
super();
}
#Override
public View onCreateView(LayoutInflater arg0, ViewGroup arg1, Bundle arg2) {
View v = super.onCreateView(arg0, arg1, arg2);
initializeMap();
return v;
}
private void initializeMap() {
GPS_Tracker gpsTracker = new GPS_Tracker(getActivity());
googleMap = getMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setScrollGesturesEnabled(true);
googleMap.getUiSettings().setTiltGesturesEnabled(true);
LatLng technoparkLocation = new LatLng(8.55765, 76.88092);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(technoparkLocation, 15));
double userLatitude = gpsTracker.getLatitude();
double userLongitude = gpsTracker.getLongitude();
pojoInstance.setUserLatitude(userLatitude);
pojoInstance.setUserLongitude(userLongitude);
LatLng userLocation = new LatLng(userLatitude, userLongitude);
googleMap.addMarker(new MarkerOptions().position(userLocation).title("User Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.map_userlocation)));
}
public void addMarkers(final ArrayList<Hostel> hostelList, Context mContext) {
this.mapContext = mContext;
for (Hostel hostel : hostelList) {
Marker marker;
if (hostel.getHostelType().equals("gents")) {
marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(hostel.getHostelLatitude(), hostel.getHostelLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_gents)).title(hostel.getName()).snippet(hostel.getPlace()));
} else if (hostel.getHostelType().equals("ladies")) {
marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(hostel.getHostelLatitude(), hostel.getHostelLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_ladies)).title(hostel.getName()).snippet(hostel.getPlace()));
} else {
marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(hostel.getHostelLatitude(), hostel.getHostelLongitude())).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_family)).title(hostel.getName()).snippet(hostel.getPlace()));
}
String markerTitle = marker.getTitle();
infoWindowHashMap.put(markerTitle, hostel);
showHostelInMap.put(markerTitle, marker);
pojoInstance.setInfoWindowHashMap(infoWindowHashMap);
pojoInstance.setShowInMap(showHostelInMap);
}
googleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
if (infoWindowHashMap.containsKey(marker.getTitle())) {
Hostel hostel = infoWindowHashMap.get(marker.getTitle());
Intent hostelIntent = new Intent(mapContext, Activity_HostelDetails.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
hostelIntent.putExtra("hostelObj", hostel);
mapContext.startActivity(hostelIntent);
}
}
});
}
public void highlightMarker(Hostel hostel) {
if (pojoInstance.getInfoWindowHashMap().containsValue(hostel)) {
String title = hostel.getName();
HashMap<String, Marker> hashMap = pojoInstance.getShowInMap();
if (hashMap.containsKey(title)) {
Marker marker = (Marker) hashMap.get(title);
googleMap.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()), 250, null);
marker.showInfoWindow();
}
}
}
}
RecylerView Fragment
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cardlist_fragment, container, false);
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.rv);
ImageView noResults = (ImageView) rootView.findViewById(R.id.no_results);
TextView noResultsText = (TextView) rootView.findViewById(R.id.no_results_text);
recyclerView.setVisibility(View.VISIBLE);
noResults.setVisibility(View.GONE);
noResultsText.setVisibility(View.GONE);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
Homescreen_Pojo.getInstance().setRecyclerView(recyclerView);
Homescreen_Pojo.getInstance().setNoResultsText(noResultsText);
Homescreen_Pojo.getInstance().setNoResultsImage(noResults);
HostelDetailsManager manager = new HostelDetailsManager(getContext(), recyclerView);
manager.jsonRequest(APIcontroller.getInstance().getURL());
return rootView;
}
}
Related
I have different fragments in my MainActivity. In each fragment I implemented some features.
Now I am trying to implemented tabs for one fragments, what I'm looking for is about hide tab layout in remaining fragments.
activity.xml:
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.genworks.oppm.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="#+id/activity_search_view_check"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="#layout/toolbar"/>
<include layout="#layout/search_toolbar"
android:visibility="gone"/>
</RelativeLayout>
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabIndicatorColor="#color/White"
app:tabTextColor="#color/White"
android:background="#drawable/button_background"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:tabGravity="fill"/>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
Fragment fragment;
int CAMERA_PIC_REQUEST=20;
Menu search_menu;
MenuItem item_search;
ExpandableListView expListView;
TabLayout tabLayout;
private ProgressDialog progressDialog = null;
TextView user,firstname,lastname,mobile,role,report_to;
String user_name;
ImageView profile;
private ArrayList<Records> records;
private ArrayList<Records> recordsList=new ArrayList<>();
ViewPager viewPager;
TextView mTitle;
private RecyclerView recyclerView;
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_GALLERY_PHOTO = 2;
File mPhotoFile;
FileCompressor mCompressor;
private RecyclerView.Adapter mAdapter;
String sessionId,username,first_name,last_name,mobile_no,role_id,reportto;
MenuItem refreshMenuItem;
ExpandableListView expandableList;
ExpandableListAdapterMenu mMenuAdapter;
List <ExpandedMenuModel> listDataHeader;
private final Handler handler = new Handler ( );
HashMap <ExpandedMenuModel, List <String>> listDataChild;
private RecyclerView.LayoutManager layoutManager;
private boolean ismenutoggle;
private Toolbar searchtollbar,toolbar;
boolean needLogin = false;
LinearLayout dashboard,taskmenu,account,contact,opportunity,logout,documents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionId = getIntent().getStringExtra("sessionId");
username = getIntent().getStringExtra("username");
PreferenceUtils.getUsername(this);
PreferenceUtils.getPassword(this);
first_name = getIntent().getStringExtra("firstname");
last_name = getIntent().getStringExtra("lastname");
mobile_no = getIntent().getStringExtra("mobile");
role_id = getIntent().getStringExtra("role");
reportto = getIntent().getStringExtra("reportto");
dashboard=findViewById(R.id.dashboard);
taskmenu=findViewById(R.id.taskmenu);
contact=findViewById(R.id.contactmenu);
opportunity=findViewById(R.id.opportunitymenu);
account=findViewById(R.id.accountmenu);
logout=findViewById(R.id.logout);
// user = (TextView) findViewById(R.id.username);
profile=findViewById(R.id.profile);
mCompressor = new FileCompressor(this);
firstname = (TextView) findViewById(R.id.firstname);
lastname = (TextView) findViewById(R.id.lastname);
mobile=findViewById(R.id.mobile);
role=findViewById(R.id.role);
report_to=findViewById(R.id.report_to);
firstname.setText(first_name);
lastname.setText(last_name);
mobile.setText(mobile_no);
role.setText(role_id);
report_to.setText(reportto);
// user.setText(username);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("DASHBOARD");
final ActionBar ab = getSupportActionBar();
ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ab.setCustomView(R.layout.toolbar_spinner);
if (ab != null) {
ab.setDisplayShowTitleEnabled(false);
mTitle = (TextView) findViewById(R.id.toolbar_title);
mTitle.setText("DASHBOARD");
mTitle.setGravity(Gravity.CENTER_HORIZONTAL);
// Typeface typeface = Typeface.createFromAsset(getApplicationContext ().getAssets (), "fonts/astype - Secca Light.otf");
// mTitle.setTypeface (typeface);
}
ab.setHomeAsUpIndicator(R.drawable.menu);
ab.setDisplayHomeAsUpEnabled(true);
//ab.setTitle ("HOME");
setSearchtollbar();
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
fragment = new DashboardFragement();
loadFragment(fragment);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
if (navigationView != null) {
setupDrawerContent (navigationView);
}
// TextView dashboard=findViewById(R.id.menu_dashboard);
dashboard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Dashboard");
fragment = new DashboardFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView task=findViewById(R.id.menu_task);
taskmenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Task List");
fragment = new TaskFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Account List");
fragment = new AccountFragement();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Contact List");
fragment = new ContactFragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView opportunity=findViewById(R.id.menu_opportunity);
opportunity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTitle.setText("Opportunity List");
fragment = new SalesStageFragment();
loadFragment(fragment);
drawerLayout.closeDrawer(GravityCompat.START);
}
});
// TextView logout=findViewById(R.id.menu_logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Intent i = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i);
finish();
drawerLayout.closeDrawer(GravityCompat.START);
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
initBottomNavigationItems();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TaskFragement(), "All");
adapter.addFragment(new AccountFragement(), "Incomplete");
adapter.addFragment(new ContactFragment(), "Scheduled");
adapter.addFragment(new ContactFragment(), "Today");
adapter.addFragment(new ContactFragment(), "Weekwise");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Gallery",
"Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivity.this);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
MainActivity.this.requestStoragePermission(true);
} else if (items[item].equals("Choose from Gallery")) {
MainActivity.this.requestStoragePermission(false);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void initBottomNavigationItems() {
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.account:
mTitle.setText("ACCOUNT LIST");
fragment = new AccountFragement();
loadFragment(fragment);
return true;
case R.id.task:
mTitle.setText("TASK LIST");
fragment = new TaskFragement();
loadFragment(fragment);
return true;
case R.id.contact:
mTitle.setText("CONTACT LIST");
fragment = new ContactFragment();
loadFragment(fragment);
return true;
case R.id.opportunity:
mTitle.setText("OPPORTUNITY LIST");
fragment = new SalesStageFragment();
loadFragment(fragment);
return true;
}
return false;
}
});
}
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
menu.findItem(R.id.search).setVisible(false);
return true;
}
private void setupDrawerContent(NavigationView navigationView) {
//revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
if(menuItem.isChecked ()){
drawerLayout.openDrawer (GravityCompat.START);}
else {
drawerLayout.closeDrawer (GravityCompat.START);
}
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(ismenutoggle==true) {
drawerLayout.openDrawer (GravityCompat.START);
ismenutoggle=false;
}
else{
drawerLayout.closeDrawer (GravityCompat.START);
ismenutoggle=true;
}
return true;
}
return super.onOptionsItemSelected(item);
}
private AdapterView.OnItemClickListener mDrawerItemClickedListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
}
};
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
finish();
}
}
private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener () {
#Override
public void onDrawerStateChanged(int status) {
}
#Override
public void onDrawerSlide(View view, float slideArg) {
}
#Override
public void onDrawerOpened(View view) {
drawerLayout.openDrawer (view);
}
#Override
public void onDrawerClosed(View view) {
drawerLayout.closeDrawer (view);
}
};
public void setSearchtollbar()
{
searchtollbar = (Toolbar) findViewById(R.id.searchtoolbar);
if (searchtollbar != null) {
searchtollbar.inflateMenu(R.menu.menu_search);
search_menu=searchtollbar.getMenu();
searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
circleReveal(R.id.searchtoolbar,1,true,false);
else
searchtollbar.setVisibility(View.GONE);
}
});
item_search = search_menu.findItem(R.id.action_filter_search);
MenuItemCompat.setOnActionExpandListener(item_search, new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
circleReveal(R.id.searchtoolbar,1,true,false);
}
else
searchtollbar.setVisibility(View.GONE);
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true;
}
});
initSearchView();
} else
Log.d("toolbar", "setSearchtollbar: NULL");
}
public void initSearchView()
{
final SearchView searchView = (SearchView) search_menu.findItem(R.id.action_filter_search).getActionView();
// Enable/Disable Submit button in the keyboard
searchView.setSubmitButtonEnabled(false);
// Change search close button image
ImageView closeButton = searchView.findViewById(R.id.search_close_btn);
closeButton.setImageResource(R.drawable.ic_close_black_24dp);
// closeButton.setImageResource(ContextCompat.getDrawable(getApplication(), R.drawable.ic_close_black_24dp));
// set hint and the text colors
EditText txtSearch = ((EditText) searchView.findViewById(R.id.search_src_text));
txtSearch.setHint("Search..");
txtSearch.setHintTextColor(Color.DKGRAY);
txtSearch.setTextColor(getResources().getColor(R.color.colorPrimary));
// set the cursor
AutoCompleteTextView searchTextView = (AutoCompleteTextView) searchView.findViewById(R.id.search_src_text);
try {
Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes");
mCursorDrawableRes.setAccessible(true);
mCursorDrawableRes.set(searchTextView, R.drawable.search_cursor); //This sets the cursor resource ID to 0 or #null which will make it visible on white background
} catch (Exception e) {
e.printStackTrace();
}
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
callSearch(query);
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
callSearch(newText);
return true;
}
public void callSearch(String query) {
Log.i("query", "" + query);
}
});
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public void circleReveal(int viewID, int posFromRight, boolean containsOverflow, final boolean isShow)
{
final View myView = findViewById(viewID);
int width=myView.getWidth();
if(posFromRight>0)
width-=(posFromRight*getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material))-(getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_material)/ 2);
if(containsOverflow)
width-=getResources().getDimensionPixelSize(R.dimen.abc_action_button_min_width_overflow_material);
int cx=width;
int cy=myView.getHeight()/2;
Animator anim;
if(isShow)
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0,(float)width);
else
anim = ViewAnimationUtils.createCircularReveal(myView, cx, cy, (float)width, 0);
anim.setDuration((long)220);
// make the view invisible when the animation is done
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(!isShow)
{
super.onAnimationEnd(animation);
myView.setVisibility(View.INVISIBLE);
}
}
});
// make the view visible and start the animation
if(isShow)
myView.setVisibility(View.VISIBLE);
// start the animation
anim.start();
}
public void setActionBarTitle(String title) {
mTitle.setText(title);
}
}
I think you are asking if we can create two tabs and when the user presses any of the tab, same fragment should appear instead of multiple fragments. If that is your question, may be i can help.
You will have to create one class that extends FragmentStateAdapter , then you should create a single class that extends Fragment instead of having multiple classes and a layout.
Create ClassFragmentPagerAdapter like this:
public class ClassFragmentPagerAdapter extends FragmentStateAdapter {
public ClassFragmentPagerAdapter (#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
if (position == 0) {
return new ClassFragment ();
}
return new ClassFragment ();
}
#Override
public int getItemCount() {
return 2;
}
Then after that create the other ClassFragment that extends Fragment:
public class ClassFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.layout_name, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
//do stuff here
}
Hope it helps! Happy coding:)
I have a MainActivity with two fragments. The second fragment has RecyclerView. There is TextView ( lesson name) and ImageView(show lesson status, if it is done or not) in RecyclerView . When you click TextView, it calls another Activity with lesson. After you make the lesson you will go back to MainActivity. After that lessons ImageView will be changed from nothing to resourse 'ic_lessondone'. Also there is a menu in MainActivity. Menu have item 'Reset lessons'. When you press 'Reset lessons' all ImageViews wont show any images. So there are two problems. 1) if I do, for example , only 6th lesson. I will have image 'lessondone'. When i press 'Reset lessons' image will disappear. But when i go back to menu again and press 'Reset lessons', Image will appear again and rise to previous lesson ( 5th). 2) If i switch off display, image will also appear to previous lessons till to 0th.
Its seems i have a problem with onResume.
Help me please.
public class MainActivity extends AppCompatActivity
{
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null)
{
setupDrawerContent(navigationView);
}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
if (viewPager != null)
{
setupViewPager(viewPager);
}
// Круглая кнопка
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
// Картинки для табов
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(R.drawable.ic_home);
tabLayout.getTabAt(1).setIcon(R.drawable.ic_lessons);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.sample_actions, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
switch (AppCompatDelegate.getDefaultNightMode())
{
case AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM:
menu.findItem(R.id.menu_night_mode_system).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_AUTO:
menu.findItem(R.id.menu_night_mode_auto).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_YES:
menu.findItem(R.id.menu_night_mode_night).setChecked(true);
break;
case AppCompatDelegate.MODE_NIGHT_NO:
menu.findItem(R.id.menu_night_mode_day).setChecked(true);
break;
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_night_mode_system:
setNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case R.id.menu_night_mode_day:
setNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case R.id.menu_night_mode_night:
setNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case R.id.menu_night_mode_auto:
setNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
break;
}
return super.onOptionsItemSelected(item);
}
private void setNightMode(#AppCompatDelegate.NightMode int nightMode)
{
AppCompatDelegate.setDefaultNightMode(nightMode);
if (Build.VERSION.SDK_INT >= 11)
{
recreate();
}
}
private void setupViewPager(ViewPager viewPager)
{
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new Fragment(), "");
adapter.addFragment(new LessonsListFragment(), "");
viewPager.setAdapter(adapter);
}
// Главное меню
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem)
{
menuItem.setChecked(true);
if (menuItem.getTitle().equals("Reset lessons"))
{
// Обнуляем файл с рузультатами уроков
LessonsListFragment.sLessonsPref.edit().clear().commit();
// Перерисовываем весь писок уроков
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
}
mDrawerLayout.closeDrawers();
return true;
}
});
}
static class Adapter extends FragmentPagerAdapter
{
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm)
{
super(fm);
}
public void addFragment(Fragment fragment, String title)
{
mFragments.add(fragment);
mFragmentTitles.add(title);
}
// Получаем конкретный фрагмент
#Override
public Fragment getItem(int position)
{
return mFragments.get(position);
}
// Количество фрагментов для viewpager (2)
#Override
public int getCount()
{
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position)
{
return mFragmentTitles.get(position);
}
}
}
Fragment
public class LessonsListFragment extends Fragment
{
// Уроки
// static private Map<String,?> mLessonsKeys ;
static SharedPreferences sLessonsPref;
static RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
loadSharedPreferenses();
rv = (RecyclerView) inflater.inflate(R.layout.fragment_cheese_list, container, false);
setupRecyclerView(rv);
return rv;
}
// Загружаем список пройденных уроков
public void loadSharedPreferenses()
{
sLessonsPref = this.getActivity().getSharedPreferences("LessonsResults", Context.MODE_PRIVATE);
}
// Количество строк в листе
private void setupRecyclerView(RecyclerView recyclerView)
{
recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext()));
recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), getRandomSublist(Cheeses.sCheeseStrings, Cheeses.sCheeseStrings.length)));
}
// Задаем Строки
private List<String> getRandomSublist(String[] array, int amount)
{
ArrayList<String> list = new ArrayList<>(amount);
//Random random = new Random();
while (list.size() < amount)
{
list.add(array[list.size()]);
}
return list;
}
//Отработка перерисования окна, при возврате к ней
#Override
public void onResume()
{
super.onResume();
//loadSharedPreferenses();
//Toast.makeText(null, "Refreshed", Toast.LENGTH_SHORT).show();
if (rv.getAdapter() != null)
{
rv.getAdapter().notifyDataSetChanged();
}
}
// Адаптер
public static class SimpleStringRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder>
{
private final TypedValue mTypedValue = new TypedValue();
private int mBackground;
private List<String> mValues;
public static class ViewHolder extends RecyclerView.ViewHolder
{
// Номер урока, передается в webactivity
public int mLessonNumber;
public final View mView;
public final ImageView mImageView;
public final TextView mTextView;
public ViewHolder(View view)
{
super(view);
mView = view;
mImageView = (ImageView) view.findViewById(R.id.avatar);
mTextView = (TextView) view.findViewById(android.R.id.text1);
}
#Override
public String toString()
{
return super.toString() + " '" + mTextView.getText();
}
}
public String getValueAt(int position)
{
return mValues.get(position);
}
public SimpleStringRecyclerViewAdapter(Context context, List<String> items)
{
context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
mBackground = mTypedValue.resourceId;
mValues = items;
}
// Создаем холдер с полезной нагрузкой
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
view.setBackgroundResource(mBackground);
return new ViewHolder(view);
}
//Создаем список уроков
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
holder.mLessonNumber = position + 1;
// Увеличиваем позицион на 1 что не было 0 урока
holder.mTextView.setText((position + 1) + " " + mValues.get(position));
// Если урок пройден
String finished = sLessonsPref.getString((position + 1) + "", "");
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
//.load(Cheeses.getRandomCheeseDrawable())
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
holder.mTextView.setTextColor(R.color.black);
// holder.mImageView.setVisibility(View.GONE);
}
// Вызов WebActivity
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Context context = v.getContext();
Intent intent = new Intent(context, WebActivity.class);
// Передаем вебвью номер урока и запускаем ее
intent.putExtra(WebActivity.EXTRA_NAME, holder.mLessonNumber);
context.startActivity(intent);
}
});
}
// Определяем количество выводимых строк
#Override
public int getItemCount()
{
return mValues.size();
}
}
}
Implement a reset() method in the adapter that mark all items as "not done" and then try:
LessonsListFragment.rv.getAdapter().reset();
LessonsListFragment.rv.getAdapter().notifyDataSetChanged();
instead of:
LessonsListFragment.rv.getAdapter().notifyItemRangeChanged(0, LessonsListFragment.rv.getAdapter().getItemCount());
inside onNavigationItemSelected.
Also, you shouldn't be using static variables (like static RecyclerView rv), use private vars with getters
The problem was in else statement. I added there this code, and now its ok. notifydatachanged work correctly from navigationview
if (finished.equals("1"))
{
// Меняем его цвет
//holder.mTextView.setTextColor(R.color.white);
Glide.with(holder.mImageView.getContext()).load(R.drawable.ic_lessondone)
.fitCenter()
.into(holder.mImageView);
Log.d("Glide", "Work");
}
else
{
Glide.with(holder.mImageView.getContext()).load(R.color.white)
.fitCenter()
.into(holder.mImageView);
holder.mTextView.setTextColor(R.color.black);
}
I want to start intent from ViewHolder class to the Fragment of Navigation Drawer Fragment class. Please see the code below.
public class LinearViewHolder extends RecyclerView.ViewHolder {
public TextView countryName;
public ImageView countryPhoto;
public Context context;
public LinearViewHolder(View v) {
super(v);
context = itemView.getContext();
countryName = (TextView) itemView.findViewById(R.id.country_name);
countryPhoto = (ImageView) itemView.findViewById(R.id.country_photo);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos == 0) {
//here we go to ActivityFragment class???
} else if (pos == 1) {
//here we go to ActivityFragment class???
} else if (pos == 2) {
//here we go to ActivityFragment class???
} else if (pos == 3) {
} else if (pos == 4) {
} else if (pos == 5) {
}
}
});
}
}
And the FragmentActivity.class code is this below!
public class ActivityFragment extends Fragment {
private List<ActivitySetData> history;
RecyclerView recList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.actvity_toolbar, container, false);
Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar_two);
setSupportActionBar(toolbar);
final CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) v.findViewById(R.id.collapsing_toolbar);
AppBarLayout appBarLayout = (AppBarLayout) v.findViewById(R.id.appbar);
appBarLayout.setExpanded(true);
// hiding & showing the title when toolbar expanded & collapsed
appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
#Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
collapsingToolbar.setTitle(getString(R.string.app_name));
isShow = true;
} else if (isShow) {
collapsingToolbar.setTitle(" ");
isShow = false;
}
}
});
try {
Glide.with(this).load(R.color.light_blue).into((ImageView) v.findViewById(R.id.backdrop));
} catch (Exception e) {
e.printStackTrace();
}
recList = (RecyclerView) v.findViewById(R.id.recycler_view);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
initializeData();
initializeAdapter();
return v;
}
private void initializeData() {
history = new ArrayList<>();
history.add(new ActivitySetData(R.color.light_blue, "Getting knowing the Activity", getString(R.string.activity_first)));
history.add(new ActivitySetData(R.color.light_blues1, "Navigation Through Activities", getString(R.string.activity_second)));
history.add(new ActivitySetData(R.color.light_blues2, "Tasks", getString(R.string.activity_third)));
history.add(new ActivitySetData(R.color.light_blues3, "The Talkback Stack", getString(R.string.activity_four)));
history.add(new ActivitySetData(R.color.light_blues4, "Activity Life Cycle", getString(R.string.activity_five)));
history.add(new ActivitySetData(R.color.light_blues6, "Activity Life Cycle Methods", getString(R.string.activity_six)));
}
private void initializeAdapter() {
ActivityAdapter adapter = new ActivityAdapter(history);
recList.setAdapter(adapter);
}
private void setSupportActionBar(Toolbar toolbar) {
}
}
And the code of my Parent MainActivity.class is below
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//Defining Variables
private NavigationView navigationView;
private DrawerLayout drawerLayout;
String showFragmentCheck;
private TextView tool;
FragmentManager mFragmentManager;
LinearLayout linearLayoutSelectLocation;
private TextView textViewCancel;
private TextView textViewLike;
private TextView textViewShare;
private ImageView ic_short;
private FloatingActionButton fab;
private static final String SHOWCASE_ID = "sequence example";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
register_view();
presentShowcaseSequence(); // one second delay
textViewLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=app.mytutoandroid"));
startActivity(browserIntent);
}
});
textViewShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=app.mytutoandroid");
startActivity(intent);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
textViewCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
linearLayoutSelectLocation.setVisibility(View.INVISIBLE);
}
});
ic_short.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, UiShortcuts.class);
// intent.putExtra("lastFragment","News");
startActivity(intent);
finish();
}
});
mFragmentManager = getSupportFragmentManager();
showFragmentCheck = getIntent().getStringExtra("checkFragment");
if (showFragmentCheck == null) {
showChildFragment("Getting Started");
} else {
showChildFragment(showFragmentCheck);
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawerLayout.closeDrawers();
showChildFragment(menuItem.getTitle().toString());
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name,
R.string.app_name);
drawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
public void register_view() {
tool = (TextView) findViewById(R.id.toolbar_title);
tool.setOnClickListener(this);
textViewLike = (TextView) findViewById(R.id.textViewLike);
textViewShare = (TextView) findViewById(R.id.textViewShare);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
textViewCancel = (TextView) findViewById(R.id.textViewCancel);
linearLayoutSelectLocation = (LinearLayout) findViewById(R.id.linearLayoutSelectLocation);
ic_short = (ImageView) findViewById(R.id.choose_short);
ic_short.setOnClickListener(this);
}
public void showChildFragment(String fragmentTitle) {
if (fragmentTitle.equals("Activity")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Activity");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ActivityFragment()).commit();
} else if (fragmentTitle.equals("Getting Started")) { // on 2nd item in the menu, do somethin
tool.setText("Android Development");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new MainFragment()).commit();
} else if (fragmentTitle.equals("Services")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Services");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ServicesFragment()).commit();
} else if (fragmentTitle.equals("Content Provider")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Content Provider");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ContentFragment()).commit();
} else if (fragmentTitle.equals("BroadCast Receiver")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to BroadCast Receiver");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new BroadCastFragment()).commit();
} else if (fragmentTitle.equals("Networking")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Networking");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new NetworkingFragment()).commit();
} else if (fragmentTitle.equals("Android Manifest")) { // on 2nd item in the menu, do somethin
tool.setText("Intro to Manifests");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new ManiFragment()).commit();
} else if (fragmentTitle.equals("References")) { // on 2nd item in the menu, do somethin
tool.setText("References");
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame, new References()).commit();
} else {
showChildFragment("Getting Started");
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.choose_short || v.getId() == R.id.toolbar_title) {
presentShowcaseSequence();
}
}
private void presentShowcaseSequence() {
ShowcaseConfig config = new ShowcaseConfig();
config.setDelay(500); // half second between each showcase view
MaterialShowcaseSequence sequence = new MaterialShowcaseSequence(this, SHOWCASE_ID);
sequence.setOnItemShownListener(new MaterialShowcaseSequence.OnSequenceItemShownListener() {
#Override
public void onShow(MaterialShowcaseView itemView, int position) {
Toast.makeText(itemView.getContext(), "Item #" + position, Toast.LENGTH_SHORT).show();
}
});
sequence.setConfig(config);
sequence.addSequenceItem(ic_short, "Shortcut for Android topics\nFind the Android Content with details.", "GOT IT");
sequence.start();
}
}
In Adapter
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = getAdapterPosition();
if (pos == 0) {
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("checkFragment", "ActivityFragment");
context.startActivity(intent);
} else if (pos == 1) {
//same as above
} else if (pos == 2) {
///same as above
} else if (pos == 3) {
} else if (pos == 4) {
} else if (pos == 5) {
}
}
});
In MainActivity
mFragmentManager = getSupportFragmentManager();
showFragmentCheck = getIntent().getStringExtra("checkFragment");
if (showFragmentCheck == null) {
showChildFragment("Getting Started");
} else {
if (showFragmentCheck.equalsIgnoreCase("ActivityFragment")) {
showChildFragment("Activity");
}else
{
showChildFragment(showFragmentCheck);
}
}
try with this way or try with this link Click Here to more
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Dependency:-
compile 'com.android.support:recyclerview-v7:21.0.0-rc1'
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
RecyclerView recList = (RecyclerView) findViewById(R.id.cardList);
recList.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recList.setLayoutManager(llm);
}
public class ContactInfo {
protected String name;
protected String surname;
protected String email;
protected static final String NAME_PREFIX = "Name_";
protected static final String SURNAME_PREFIX = "Surname_";
protected static final String EMAIL_PREFIX = "email_";
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected TextView vSurname;
protected TextView vEmail;
protected TextView vTitle;
public ContactViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.txtName);
vSurname = (TextView) v.findViewById(R.id.txtSurname);
vEmail = (TextView) v.findViewById(R.id.txtEmail);
vTitle = (TextView) v.findViewById(R.id.title);
}
}
public class ContactAdapter extends
RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
private List<ContactInfo> contactList;
public ContactAdapter(List<ContactInfo> contactList) {
this.contactList = contactList;
}
#Override
public int getItemCount() {
return contactList.size();
}
#Override
public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) {
ContactInfo ci = contactList.get(i);
contactViewHolder.vName.setText(ci.name);
contactViewHolder.vSurname.setText(ci.surname);
contactViewHolder.vEmail.setText(ci.email);
contactViewHolder.vTitle.setText(ci.name + " " + ci.surname);
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.card_layout, viewGroup, false);
return new ContactViewHolder(itemView);
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
...
}
}
I have a really interesting problem with my Navigator menu.
I have no idea why... But I can click on any item from my menu, I don't want to say I click and nothing happened. I really want to say I can't click on any item, all my menu it's like a big image.
I've try to make a new project witch already have Navigation Drawer Activity, of course it works.. but when I've try to copy that code and put on mine.. I have the same problem and vice versa, I've try to put my code into a new project with Navigation Drawer Activity, but again... I can't click on any item.
Here it's one image with my aplication.
Here it's my Main Activity:
public class MainActivity extends Activity implements NavigationDrawerFragment.NavigationDrawerCallbacks, AdapterView.OnItemClickListener {
ArrayList<Trail> arrayTrail;
ListView listViewTrails;
ArrayList<Wonder> arrayWonders1;
ArrayList<Wonder> arrayWonders2;
ArrayList<Wonder> arrayWonders3;
ArrayList<Wonder> arrayWonders4;
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
arrayWonders1 = new ArrayList<>();
arrayWonders2 = new ArrayList<>();
arrayWonders3 = new ArrayList<>();
arrayWonders4 = new ArrayList<>();
arrayWonders1.add(new Wonder("https://risehighershinebrighter.files.wordpress.com/2014/11/magic-of-blue-universe-images.jpg", "Ceva", "100"));
arrayWonders1.add(new Wonder("http://i765.photobucket.com/albums/xx291/just-meller/national%20geografic/Birds-national-geographic-6873734-1600-1200.jpg", "Ceva", "20"));
arrayWonders2.add(new Wonder("hhttp://www.freestockphotos.name/wallpaper-original/wallpapers/download-images-of-gentle-dogs-6866.jpg", "Ceva", "400"));
arrayWonders2.add(new Wonder("http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg", "Ceva", "200"));
arrayWonders3.add(new Wonder("http://hdwallnpics.com/wp-content/gallery/hd-tiger-images/tigers-wallpapers-hd.jpg", "Ceva", "100"));
arrayWonders3.add(new Wonder("http://imgscenter.com/images/2014/09/13/6-autumn-nature-sandbox-images_2053316.jpg", "Ceva", "100"));
arrayWonders4.add(new Wonder("http://www.tollywooddaily.com/wp-content/uploads/2015/05/HORIZONTAL-BABY-HIGHRES-EMPTY.jpg", "Ceva", "100"));
arrayWonders4.add(new Wonder("http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg", "Ceva", "100"));
arrayTrail = new ArrayList<>();
Trail audi = new Trail("http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg", "Paris", "Popular Destination", "htrhetgftrwfrec", "Story", arrayWonders1);
Trail opel = new Trail("http://www.gettyimages.com/gi-resources/images/CreativeImages/Hero-527920799.jpg", "Romania", "Popular Destination", "fewfwefwefWgfeg", "Story", arrayWonders2);
Trail mercedes = new Trail("http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg", "Italia", "Popular Destination", "gtrhrthtrhrw", "Story", arrayWonders3);
Trail ferrari = new Trail("http://saturn.jpl.nasa.gov/multimedia/images/moons/images/PIA07759.jpg", "Roma", "Popular Destination", "dajfuisndfisndfs", "Story", arrayWonders4);
Trail fiesta = new Trail("http://www.quicksprout.com/images/foggygoldengatebridge.jpg", "Bucuresti", "Popular Destination", "regehgtrhrjhjy", "Story", arrayWonders1);
Trail porshe = new Trail("http://3.bp.blogspot.com/-rZmCIp0C-hQ/Tx6aCFeweoI/AAAAAAAAAnQ/WqIEVBTIzRk/s1600/Cool-Tiger-Wallpaper-1920x1080-HD.jpg", "Luxemburg", "Popular Destination", "Ffdsjifsdfmskodmf", "Story", arrayWonders2);
arrayTrail.add(audi);
arrayTrail.add(opel);
arrayTrail.add(mercedes);
arrayTrail.add(ferrari);
arrayTrail.add(fiesta);
arrayTrail.add(porshe);
listViewTrails = (ListView) findViewById(R.id.list_trails);
ListTailsAdapter adapter = new ListTailsAdapter(this, arrayTrail);
listViewTrails.setAdapter(adapter);
listViewTrails.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Trail selectedTrail = arrayTrail.get(position);
Intent intent = new Intent(this, TrailActivity.class);
intent.putExtra("trail", selectedTrail);
startActivity(intent);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.main_menu_search) {
ArrayList<Trail> trails = arrayTrail;
Intent intent = new Intent(this, SearchActivity.class);
intent.putExtra("trailsSearch", trails);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
And here it Navigation Drawer Fragment class:
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.categori_1),
getString(R.string.categori_2),
getString(R.string.categori_3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.drawable.ic_drawer,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
public static interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
}
So if anyone of you guys have any idea... Please tell me, I really need to fix it as soon as possible and in this moment I don't have any idea how..
Thx for your help :)
this code work for me
public class MyDrawer extends AppCompatActivity {
ActionBarDrawerToggle toggle;
// other code
super.setContentView(fullLayout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout3);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
drawer.closeDrawers();
int itemId = menuItem.getItemId();
//Toast.makeText(getApplicationContext(), menuItem.getTitle().toString(),
// Toast.LENGTH_LONG).show();
int id = menuItem.getItemId();
if (id == R.id.nav_camara) {
update();
// Handle the camera action
} else if (id == R.id.nav_gallery) {
Intent intent = new Intent(getApplicationContext(), AndroidListViewCursorAdaptorActivity.class);
startActivity(intent);
// } else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
Intent intent = new Intent(getApplicationContext(), Manage.class);
startActivity(intent);
} else if (id == R.id.nav_about) {
Intent intent = new Intent(getApplicationContext(), About.class);
startActivity(intent);
}
else if (id == R.id.nav_cantect) {
Intent intent = new Intent(getApplicationContext(), AboutCantect.class);
startActivity(intent);
}
//navigationView.getMenu().findItem(R.id.drawer_5_reasons).setChecked(true);
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (toggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
Hello everyone I am developing an android app and I am new to this development.
I am facing on error which says:
Error:(134, 19) error: RecyclerTouchListener is not abstract and does not override abstract method onRequestDisallowInterceptTouchEvent(boolean) in OnItemTouchListener
Here is my code from where the above error appears
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
/* public void myClickMethod(View v) {
switch(v.getid()) {
// Just like you were doing
}
}*/
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
MainActivity.java
public class MainActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private CharSequence mDrawerTitle;
private ActionBar actionBar;
// used to store app title
private CharSequence mTitle;
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
private ActionBarDrawerToggle mDrawerToggle;
private Fragment fra;
// FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setAlpha(50);
mToolbar = (Toolbar) findViewById(R.id.tool_bar1);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.logofinal);
mTitle = mDrawerTitle = getTitle();
/* getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);*/
drawerFragment = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
/**
* Creating all buttons instances
* */
// Dashboard News feed button
/*Button btn_newsfeed = (Button)findViewById(R.id.btn_news_feed);
btn_newsfeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.btn_news_feed:
fra= new HomeFragment();
break;
}
}
});
Button btn_friends = (Button) findViewById(R.id.btn_events);
btn_friends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch(view.getId())
{
case R.id.btn_events:
fra= new ContactFragment();
break;
}
}
});*/
// Dashboard Friends button
Button btn_newsfeed = (Button)findViewById(R.id.btn_news_feed);
Button btn_friends = (Button) findViewById(R.id.btn_friends);
// Dashboard Messages button
Button btn_messages = (Button) findViewById(R.id.btn_messages);
// Dashboard Places button
Button btn_places = (Button) findViewById(R.id.btn_places);
// Dashboard Events button
Button btn_events = (Button) findViewById(R.id.btn_events);
// Dashboard Photos button
Button btn_photos = (Button) findViewById(R.id.btn_photos);
//Button btn_Maps = (Button) findViewById(R.id.btn_maps);
/**
* Handling all button click events
* */
// Listening to News Feed button click*/
btn_friends.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(MainActivity.this, AboutActivity.class);
startActivity(i);
}
});
// Listening Friends button click
btn_newsfeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(MainActivity.this, HomeFragment.class);
startActivity(i);
}
});
// Listening Messages button click
btn_messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(MainActivity.this, MessagesFragment.class);
startActivity(i);
}
});
// Listening to Places button click
btn_places.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(MainActivity.this, FriendsFragment.class);
startActivity(i);
}
});
// Listening to Events button click
btn_events.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(MainActivity.this, CampusFragment.class);
startActivity(i);
}
});
// Listening to Photos button click
btn_photos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(MainActivity.this, ContactFragment.class);
startActivity(i);
}
});
}
/* public void myClickmethod(View v) {
switch (v.getId()) {
case R.id.btn_news_feed:
Intent i = new Intent(MainActivity.this, HomeFragment.class);
startActivity(i);
break;
default:
break;
}
}*/
#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;
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
#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;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
Intent intent;
String title = getString(R.string.app_name);
switch (position) {
case 0:
Intent i = new Intent(MainActivity.this, HomeFragment.class);
title = getString(R.string.title_home);
startActivity(i);
break;
case 1:
i = new Intent(MainActivity.this, FriendsFragment.class);
title = getString(R.string.title_friends);
startActivity(i);
break;
case 2:
Intent i2=new Intent(getApplicationContext(),MessagesFragment.class);
title = getString(R.string.title_messages);
startActivity(i2);
break;
/* case 3:
Intent i1 = new Intent(MainActivity.this, FriendsFragment.class);
startActivity(i1);
title = getString(R.string.title_department);
startActivity(i1);
break;*/
case 3:
i = new Intent(MainActivity.this, CampusFragment.class);
title = getString(R.string.title_campus_life);
startActivity(i);
break;
case 4:
i = new Intent(MainActivity.this, ContactFragment.class);
title = getString(R.string.title_contact);
startActivity(i);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
public void onBackPressed() {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Are you sure you want to exit?");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
}
);
alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// We do nothing
}
});
alertDlg.create().show();
}
}
Would be grateful if anyone helps me.
It sounds like you just need to override the onRequestDisallowTouchEvent() method on your RecyclerTouchListener.
Try adding this within your RecyclerTouchListener class:
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
So.. your code should now look like this:
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept){
}
}
You can refer to this question for more info.
I hope this helps!
Your code is missing one method:
onRequestDisallowInterceptTouchEvent(boolean disallowIntercept)
See in: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.OnItemTouchListener.html
Inside your RecyclerTouchListener class, you need to add this:
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
//Any desired code
}