I am developing news app user can download video and image.
So I developed navigation drawer with different fragment with material design. But I am facing some problem in it when I click gallery (where I show the downloaded video and images) it stuck for some time and then open fragment. it happened only in specific fragment but not all.
see Video here.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
TextView mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null)
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
mTitle = (TextView) mToolbar.findViewById(R.id.tv_toolbar_title);
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);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
/* if (id == R.id.action_search) {
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}*/
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
mTitle.setText(title);
break;
case 1:
fragment = new GalleryFragment();
title = getString(R.string.title_gallery);
mTitle.setText(title);
break;
case 2:
fragment = new SettingFragment();
title = getString(R.string.title_setting);
mTitle.setText(title);
break;
case 3:
fragment = new AboutusFragment();
title = getString(R.string.title_aboutus);
mTitle.setText(title);
break;
case 4:
fragment = new ContactusFragment();
title = getString(R.string.title_contactus);
mTitle.setText(title);
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
if (getSupportActionBar() != null)
getSupportActionBar().setTitle(title);
}
}
}
FragmentDrawer.java
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private static DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private static int[] ic_nav_drw = {R.drawable.ic_setting, R.drawable.gallery, R.drawable.setting, R.drawable.aboutus, R.drawable.contactus};
private FragmentDrawerListener drawerListener;
ImageView profile;
TextView tv_name;
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]);
navItem.setIcon(ic_nav_drw[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);
tv_name = (TextView) layout.findViewById(R.id.tv_name);
profile = (ImageView) layout.findViewById(R.id.profile);
SharedPreferences settings = getActivity().getSharedPreferences("preference", 0);
String name = settings.getString("name","");
tv_name.setText(name);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "You click profile", Toast.LENGTH_SHORT).show();
}
});
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) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
activity_main.xml
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.bicubic.botadnews.fragment.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
fragment_navigation_drawer.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/nav_header_container"
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary">
<ImageView
android:id="#+id/profile"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_centerInParent="true"
android:scaleType="fitCenter"
android:src="#drawable/ic_profile" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textColor="#color/white"
android:textSize="20sp"
android:layout_marginBottom="10dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/nav_header_container"
android:layout_marginTop="15dp" />
</RelativeLayout>
Here is my gallery fragment
Editted GalleryFragment.java
public class GalleryFragment extends Fragment implements View.OnClickListener {
View rootView;
static RecyclerView rv_video;
RecyclerView rv_image;
static List<File> videofiles;
static List<File> imagefiles;
Button bt_video, bt_image;
private static Context context ;
public GalleryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
rv_video = (RecyclerView) rootView.findViewById(R.id.rv_video);
rv_image = (RecyclerView) rootView.findViewById(R.id.rv_image);
bt_video = (Button) rootView.findViewById(R.id.bt_video);
bt_image = (Button) rootView.findViewById(R.id.bt_image);
bt_video.setBackgroundResource(R.color.colorAccent);
bt_video.setOnClickListener(this);
bt_image.setOnClickListener(this);
context = getActivity();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
rv_video.setLayoutManager(linearLayoutManager);
rv_video.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getActivity());
rv_image.setLayoutManager(linearLayoutManager1);
rv_image.setHasFixedSize(true);
videofiles = new ArrayList<>();
imagefiles = new ArrayList<>();
new LoadOfflineData().execute();
rootView.post(new Runnable() {
#Override
public void run() {
new LoadOfflineData().execute();
}
});
// Inflate the layout for this fragment
return rootView;
}
public static class LoadOfflineData extends AsyncTask<Void, Void, Void> {
ProgressDialog progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = new ProgressDialog(context);
progressBar.setMessage("Loading...");
progressBar.show();
}
#Override
protected Void doInBackground(Void... voids) {
String video_path = Environment.getExternalStorageDirectory().getPath() + "/Botad News/Videos";
Log.d("Files", "Path: " + video_path);
File checkFile = new File(video_path);
// videofiles = new ArrayList<>();
File[] files = new File[0];
if (checkFile.isDirectory()) {
File directory = new File(video_path);
files = directory.listFiles();
videofiles.addAll(Arrays.asList(files));
} else {
// Toast.makeText(getActivity(), "Folder not Found", Toast.LENGTH_SHORT).show();
Log.e(TAG, "doInBackground: folder not found" );
}
String image_path = Environment.getExternalStorageDirectory().getPath() + "/Botad News/Images";
Log.d("Files", "Path: " + image_path);
File checkFileImages = new File(image_path);
// imagefiles = new ArrayList<>();
File[] filesImage = new File[0];
if (checkFileImages.isDirectory()) {
File directory = new File(image_path);
filesImage = directory.listFiles();
imagefiles.addAll(Arrays.asList(filesImage));
} else {
// Toast.makeText(getActivity(), "Folder not Found", Toast.LENGTH_SHORT).show();
Log.e(TAG, "doInBackground: folder not found" );
}
Log.d("Files", "Size: " + files.length);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressBar.dismiss();
if (videofiles.size() > 0) {
RvGalleryVideoAdapter adapter = new RvGalleryVideoAdapter(videofiles, context);
rv_video.setAdapter(adapter);
} else {
Toast.makeText(context, "Data not found", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bt_video:
bt_video.setBackgroundResource(R.color.colorAccent);
bt_image.setBackgroundResource(R.color.colorPrimary);
rv_image.setVisibility(View.GONE);
rv_video.setVisibility(View.VISIBLE);
if (videofiles.size() > 0) {
RvGalleryVideoAdapter adapter = new RvGalleryVideoAdapter(videofiles, getActivity());
rv_video.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
break;
case R.id.bt_image:
bt_image.setBackgroundResource(R.color.colorAccent);
bt_video.setBackgroundResource(R.color.colorPrimary);
rv_image.setVisibility(View.VISIBLE);
rv_video.setVisibility(View.GONE);
if (imagefiles.size() > 0) {
RvGalleryImageAdapter adapter_image = new RvGalleryImageAdapter(imagefiles, getActivity());
rv_image.setAdapter(adapter_image);
} else {
Toast.makeText(getActivity(), "Data not found", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
}
In your AsyncTask, you are accessing the class fields of the Fragment! This will actually block the UI Thread :-(
The lines
videofiles = new ArrayList<>();
imagefiles = new ArrayList<>();
cannot be there. You need to create local lists, put data in them and then return it in onPostExecute().
Start by replacing
public class LoadOfflineData extends AsyncTask<Void, Void, Void> {
with
public static class LoadOfflineData extends AsyncTask<Void, Void, Void> {
This will give you errors in places you need to change :-)
I found the answer.
It is in my RecyclerAdapter when i get thumbnail using inbuilt class so it will take time to set it see my
Old code
Bitmap bmThumbnail;
//MICRO_KIND, size: 96 x 96 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(sdcard_path + "/Botad News/Videos/" + fileName, MediaStore.Images.Thumbnails.MICRO_KIND);
holder.img_main.setImageBitmap(bmThumbnail);
New code is using glide library so lib automatically handle the thread i assume.
BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
int microSecond = 6000000;// 6th second as an example
VideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond);
FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888);
Glide.with(context)
.load(sdcard_path + "/Botad News/Videos/" + fileName)
.asBitmap()
.override(250,250)// Example
.videoDecoder(fileDescriptorBitmapDecoder)
.into(holder.img_main);
Found solution HERE....
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:)
Here i am using NavigationDrawer for my activities.It is working fine.i am using Recyclerview for displaying NavigationDrawer items. Now i want to display different NavigationDrawer Item for different Activity..Here i am using nav_drawer_labels in FragmentDrawer to display items.How to display nav_drawer_labels1 in another activity.I mean i have to display different NavigationDrawer in each activity..here is my code.
CompProfileDisplay.java
public class CompProfileDisplay extends AppCompatActivity implements OnItemClickListener, FragmentDrawer.FragmentDrawerListener {
private static String TAG = CompProfileDisplay.class.getSimpleName();
private MenuItem menuitems;
private Toolbar mToolbar;
private FragmentDrawer drawerFragment1;
private ImageView img;
private int count;
private TextView textView;
private String doc;
public static final String UPLOAD_URL = "http://website.com/aboutme_update.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.compprofile_display);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
img = (ImageView) findViewById(R.id.imageView10);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
final Context context = this;
drawerFragment1 = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment1.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment1.setDrawerListener(this);
// display the second navigation drawer view on app launch
displayView(0);
SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);
SharedPreferences sharedPreferences1 = getSharedPreferences(ClickToComp.SHARED_PREF_NAME, MODE_PRIVATE);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);//no title in dialog.
dialog.getWindow().setBackgroundDrawable( new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.im);
Typeface font = Typeface.createFromAsset( getAssets(), "fontawesome-webfont.ttf" );
TextView txt = (TextView) dialog.findViewById(R.id.custom_fullimage_placename);
txt.setTypeface(font);
String url1 = "http://www.website.com/" + doc;
new DownloadImageTask((ImageView) dialog.findViewById(R.id.fullimage))
.execute(url1);
//on click of cancel icon/btn popup screen will close.
txt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
});
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent;
switch (position) {
default:
intent = new Intent(CompProfileDisplay.this, Banking.class);
startActivity(intent);
break;
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.testAction);
menuItem.setIcon(buildCounterDrawable(count, R.drawable.add));
return true;
}
private Drawable buildCounterDrawable(int count, int backgroundImageId) {
LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.action_bar_notifitcation_icon, null);
view.setBackgroundResource(backgroundImageId);
if (count == 0) {
View counterTextPanel = view.findViewById(R.id.counterValuePanel);
counterTextPanel.setVisibility(View.GONE);
} else {
textView = (TextView) view.findViewById(R.id.count);
textView.setText("" + count);
textView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CompProfileDisplay.this, "You have new friend request", Toast.LENGTH_SHORT).show();
}
});
}
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return new BitmapDrawable(getResources(), bitmap);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.testAction) {
if(count>0) {
Toast.makeText(getApplicationContext(), "You have new friend request", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "You dont have any new notification", Toast.LENGTH_SHORT).show();
}
return true;
}
if(id == R.id.action_search){
/*Toast.makeText(getApplicationContext(), vault_no, Toast.LENGTH_SHORT).show();
return true;*/
//logout();
}
if(id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
/*fragment = new HomeFragment();*/
title = "Profile";
break;
case 1:
/*fragment = new ProfileFragment();
title = getString(R.string.title_profile);
break;*/
startActivity(new Intent(this, CompProfileDisplay.class));
return;
case 2:
startActivity(new Intent (this,DisplayContact.class));
return;
case 3:
startActivity(new Intent(this, DocUpload.class));
return;
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);
}
}
}
FragmentDrawer.class
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
public static final String SHARED_PREF_NAME = "myloginapp";
private RecyclerView recyclerView;
private String doc;
private String fullname;
private String vault;
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);
// here i am displaying nav_drawer_labels items in one activity.
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
//i want to display nav_drawer_labels1 in another activity.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
ImageView img = (ImageView)layout.findViewById(R.id.img);
TextView name = (TextView)layout.findViewById(R.id.name);
TextView vault_no = (TextView)layout.findViewById(R.id.vault);
SharedPreferences sharedPreferences1 = this.getActivity().getSharedPreferences(FragmentDrawer.SHARED_PREF_NAME, Context.MODE_PRIVATE);
vault = sharedPreferences1.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences(FragmentDrawer.SHARED_PREF_NAME, Context.MODE_PRIVATE);
doc = sharedPreferences.getString(ClickToLogin.DOC_SHARED_PREF,"Not Available");
fullname = sharedPreferences.getString(ClickToLogin.FULLNAME_SHARED_PREF,"Not Available");
name.setText(fullname);
vault_no.setText(vault);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
String url1 = "http://www.miisky.com/"+doc;
new DownloadImageTask((ImageView) layout.findViewById(R.id.img))
.execute(url1);
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;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
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) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="nav_item_home1">Home</string>
<string name="nav_item_profile1">Profile</string>
<string name="nav_item_customersupport">Customer Support</string>
<string name="nav_item_dealer">Dealer Network</string>
<string-array name="nav_drawer_labels1">
<item>#string/nav_item_home1</item>
<item>#string/nav_item_profile1</item>
<item>#string/nav_item_customersupport</item>
</string-array>
<string name="nav_item_home">Home</string>
<string name="nav_item_profile">Profile</string>
<string name="nav_item_contacts">Contacts</string>
<string name="nav_item_docupload">Upload Documents</string>
<!-- navigation drawer item labels -->
<string-array name="nav_drawer_labels">
<item>#string/nav_item_home</item>
<item>#string/nav_item_profile</item>
<item>#string/nav_item_contacts</item>
</string-array>
</resources>
Navigation drawer is meant to be used with fragments.
The main activity host the the nav drawer.
Fragments make it easy to swap the drawer content a keep its state.
If you wanted to use acitvity instead then you should create a base activity conaining the drawer so that all your activities inherit from that activity.
This way the nav drawer can persist from activity to activity.
I want to create Multi-Level Menus in drawer Layout. My Activity.xml:-
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.android.ShoppingMazza.activity.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
Here My fragment_navigation_drawer.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white">
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp" />
Here My 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) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
Here My MainActivity.java:-
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
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);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
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);
}
}
}
My Current View of App below:-
but i want multi-level submenus (more than 3) in Home menu.
I am new in android developing help me. Thanks in advance
You can simply use Android TreeView Library.
Reference: https://github.com/bmelnychuk/AndroidTreeView
And if you just need three levels, you can create a threelevel custom expandable listview.
Reference: https://github.com/talhahasanzia/Three-Level-Expandable-Listview
You can use ExpandableListView instead of RecyclerView. Here is a nice tutorial to implement it.
Expandable ListView
And if you really want to use RecyclerView you can look at the following library:
Expandable RecyclerView
after some modifications on my app, i can see that it works on abdroid studio emulator, the items in the navigation drawer are there, but when i install the app with apk on my mobile, i cant see the items but i can click on.
MainActivity.java:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
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);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Accueil/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);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new Accueil();
title = getString(R.string.title_accueil);
break;
case 1:
fragment = new NosOffres();
title = getString(R.string.title_nosoffres);
break;
case 2:
fragment = new ContactezNous();
title = getString(R.string.title_contact);
break;
case 3:
fragment = new Actualites();
title = getString(R.string.title_actu);
break;
case 4:
fragment = new MentionsLegales();
title = getString(R.string.title_mentions);
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
TextView titlet;
titlet = (TextView) findViewById(R.id.main_toolbar_title);
titlet.setText(title);
titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
}
}
}
NavigationDrawerAdapter.java:
public class NavigationDrawerAdapter extends RecyclerView.Adapter<NavigationDrawerAdapter.MyViewHolder> {
List<NavDrawerItem> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
public NavigationDrawerAdapter(Context context, List<NavDrawerItem> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}
public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.nav_drawer_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title);
title.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/GothamBook.ttf"));
}
}
}
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.getChildAdapterPosition(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.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
But i think the error is in the xml files, because i haven't touched the java class, but only xml layout files before the problem:
nav_drawer_row.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="50px"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textSize="15dp"
android:textColor="#ffffff"
android:gravity="center_vertical"
android:textIsSelectable="false" />
</RelativeLayout>
activity_main.xml:
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<FrameLayout
android:id="#+id/container_body"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="fr.solutis.solutis.FragmentDrawer"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
These 2 xml layour are in res/layout but i didn't do the same in res/layout-normal, but i think it's not a problem.
That was the height, it was so small ! So edit nav_drawer_row.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true">
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="150px"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textSize="15dp"
android:textColor="#ffffff"
android:gravity="center_vertical"
android:textIsSelectable="false" />
</RelativeLayout>
I have a navigation Drawer in my App. If i select a particular item and slide the navigation drawer. The Fragment overlaps the navigation Drawer.
I Tried to add popBackStackImmediate(); But it is of no use. This is how it looks like
Activity
public class Activity extends MainActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
// TODO Auto-generated method stub
if (position == 1)
{
HomeFragment Frag = new HomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, Frag);
transaction.commit();
}
else if (position == 2)
{
}
}
public void onDrawerOpened(View drawerview)
{
getFragmentManager().popBackStackImmediate();
}
Navigation Fragment
public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks
{
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREFERENCES_FILE = "my_app_settings";
private NavigationDrawerCallbacks mCallbacks;
private RecyclerView mDrawerList;
private View mFragmentContainerView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private int mCurrentSelectedPosition;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mDrawerList.setLayoutManager(layoutManager);
mDrawerList.setHasFixedSize(true);
final List<NavigationItem> navigationItems = getMenu();
NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems);
adapter.setNavigationDrawerCallbacks(this);
mDrawerList.setAdapter(adapter);
selectItem(mCurrentSelectedPosition);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null)
{
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
}
#Override
public void onAttach(Activity activity)
{
super.onAttach(activity);
try
{
mCallbacks = (NavigationDrawerCallbacks) activity;
}
catch (ClassCastException e)
{
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
public ActionBarDrawerToggle getActionBarDrawerToggle()
{
return mActionBarDrawerToggle;
}
public void setActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle)
{
mActionBarDrawerToggle = actionBarDrawerToggle;
}
public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar)
{
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.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;
saveSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "true");
}
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState)
mDrawerLayout.openDrawer(mFragmentContainerView);
mDrawerLayout.post(new Runnable()
{
#Override
public void run()
{
mActionBarDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
public void openDrawer()
{
mDrawerLayout.openDrawer(mFragmentContainerView);
}
public void closeDrawer()
{
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
#Override
public void onDetach()
{
super.onDetach();
mCallbacks = null;
}
public List<NavigationItem> getMenu()
{
List<NavigationItem> items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("Home", getResources().getDrawable(R.drawable.play)));
items.add(new NavigationItem("News", getResources().getDrawable(R.drawable.play)));
items.add(new NavigationItem("Videos", getResources().getDrawable(R.drawable.play)));
items.add(new NavigationItem("Playlist", getResources().getDrawable(R.drawable.play)));
return items;
}
void selectItem(int position)
{
mCurrentSelectedPosition = position;
if (mDrawerLayout != null)
{
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null)
{
mCallbacks.onNavigationDrawerItemSelected(position);
}
((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position);
}
public boolean isDrawerOpen()
{
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onNavigationDrawerItemSelected(int position)
{
mCallbacks.onNavigationDrawerItemSelected(position);
selectItem(position);
}
public DrawerLayout getDrawerLayout()
{
return mDrawerLayout;
}
public void setDrawerLayout(DrawerLayout drawerLayout)
{
mDrawerLayout = drawerLayout;
}
}
Activity Layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar_actionbar"
layout="#layout/toolbar_default"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar_actionbar">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!-- android:layout_marginTop="?android:attr/actionBarSize"-->
<fragment
android:id="#+id/fragment_drawer"
android:name="com.RemoteIt.client.activity.drawer.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
HomeFragment
public class HomeFragment extends Fragment
{
public HomeFragment()
{}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{ View v = inflater.inflate(R.layout.home, container, false);
int redActionButtonSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_size);
int redActionButtonMargin = getResources().getDimensionPixelOffset(R.dimen.action_button_margin);
int redActionButtonContentSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size);
int redActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_margin);
int redActionMenuRadius = getResources().getDimensionPixelSize(R.dimen.red_action_menu_radius);
int blueSubActionButtonSize = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_size);
int blueSubActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_content_margin);
ImageView fabIconStar = new ImageView(getActivity());
fabIconStar.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_important));
FloatingActionButton.LayoutParams starParams = new FloatingActionButton.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
starParams.setMargins(redActionButtonMargin, redActionButtonMargin, redActionButtonMargin, redActionButtonMargin);
fabIconStar.setLayoutParams(starParams);
FloatingActionButton.LayoutParams fabIconStarParams = new FloatingActionButton.LayoutParams(redActionButtonContentSize, redActionButtonContentSize);
fabIconStarParams.setMargins(redActionButtonContentMargin, redActionButtonContentMargin, redActionButtonContentMargin, redActionButtonContentMargin);
FloatingActionButton leftCenterButton = new FloatingActionButton.Builder(getActivity()).setContentView(fabIconStar, fabIconStarParams).setBackgroundDrawable(R.drawable.button_action_red_selector).setPosition(FloatingActionButton.POSITION_TOP_CENTER).setLayoutParams(starParams).build();
// Set up customized SubActionButtons for the right center menu
SubActionButton.Builder lCSubBuilder = new SubActionButton.Builder(getActivity());
lCSubBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_action_blue_selector));
FrameLayout.LayoutParams blueContentParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
blueContentParams.setMargins(blueSubActionButtonContentMargin, blueSubActionButtonContentMargin, blueSubActionButtonContentMargin, blueSubActionButtonContentMargin);
lCSubBuilder.setLayoutParams(blueContentParams);
// Set custom layout params
FrameLayout.LayoutParams blueParams = new FrameLayout.LayoutParams(blueSubActionButtonSize, blueSubActionButtonSize);
lCSubBuilder.setLayoutParams(blueParams);
ImageView lcIcon1 = new ImageView(getActivity());
ImageView lcIcon2 = new ImageView(getActivity());
ImageView lcIcon3 = new ImageView(getActivity());
ImageView lcIcon4 = new ImageView(getActivity());
ImageView lcIcon5 = new ImageView(getActivity());
ImageView lcIcon6 = new ImageView(getActivity());
ImageView lcIcon7 = new ImageView(getActivity());
ImageView lcIcon8 = new ImageView(getActivity());
ImageView lcIcon9 = new ImageView(getActivity());
lcIcon1.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_camera));
lcIcon2.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_picture));
lcIcon3.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_video));
lcIcon4.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_location_found));
lcIcon5.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_headphones));
lcIcon6.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_camera));
lcIcon7.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_picture));
lcIcon8.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_video));
lcIcon9.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_location_found));
// Build another menu with custom options
FloatingActionMenu leftCenterMenu = new FloatingActionMenu.Builder(getActivity()).addSubActionView(lCSubBuilder.setContentView(lcIcon1, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon2, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon3, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon4, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon5, blueContentParams).build())
.addSubActionView(lCSubBuilder.setContentView(lcIcon6, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon7, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon8, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon9, blueContentParams).build()).setRadius(redActionMenuRadius).setStartAngle(0).setEndAngle(360).attachTo(leftCenterButton).build();
return v;
}
}
The following changes were made to the FloatingActionButton and FloatingActionMenu classes to allow a specific ViewGroup to be set as the container for both. Tests were made with a similar but simpler version of the code you've posted, so you may need to make adjustments to your setup parameters.
The library code assumes that the Button and Menu are to appear on top of an Activity's content View, and everything therein. The addition of a container ViewGroup member in the FloatingActionButton class allows us to specify a child ViewGroup to be the parent instead. Please note that the following changes will only work if a FloatingActionButton is used with the Menu.
The additions to the FloatingActionButton class:
public class FloatingActionButton extends FrameLayout {
...
private ViewGroup containerView;
...
public FloatingActionButton(Activity activity,
LayoutParams layoutParams,
int theme,
Drawable backgroundDrawable,
int position,
View contentView,
FrameLayout.LayoutParams contentParams
// Note the addition of the following
// constructor parameter here
, ViewGroup containerView) {
...
setClickable(true);
// This line is new. The rest of the constructor is the same.
this.containerView = containerView;
attach(layoutParams);
}
...
public View getActivityContentView() {
if(containerView == null) {
return ((Activity)getContext())
.getWindow().getDecorView().findViewById(android.R.id.content);
} else {
return containerView;
}
}
public ViewGroup getContainerView() {
return containerView;
}
// The following setter is not strictly necessary, but may be of use
// if you want to toggle the Button's and Menu's z-order placement
public void setContainerView(ViewGroup containerView) {
this.containerView = containerView;
}
...
public static class Builder {
...
private ViewGroup containerView;
...
public Builder setContainerView(ViewGroup containerView) {
this.containerView = containerView;
return this;
}
public FloatingActionButton build() {
return new FloatingActionButton(activity,
layoutParams,
theme,
backgroundDrawable,
position,
contentView,
contentParams,
// New argument
containerView);
}
}
...
}
And the changes to the FloatingActionMenu class:
public class FloatingActionMenu {
...
public View getActivityContentView() {
if(mainActionView instanceof FloatingActionButton &&
((FloatingActionButton) mainActionView).getContainerView() != null) {
return ((FloatingActionButton) mainActionView).getContainerView();
} else {
return ((Activity)mainActionView.getContext())
.getWindow().getDecorView().findViewById(android.R.id.content);
}
}
...
}
Then, in the Fragment's onCreateView() method, we need to add a call the new setContainerView() method of the FloatingActionButton.Builder class.
public class HomeFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
...
FloatingActionButton leftCenterButton = new FloatingActionButton.Builder(getActivity())
.setContentView(fabIconStar, null)
.setBackgroundDrawable(R.drawable.ic_launcher)
.setPosition(FloatingActionButton.POSITION_TOP_CENTER)
.setLayoutParams(starParams)
// The new method call is added here
.setContainerView(container)
.build();
...
}
...
}
Please replace the below line of code
transaction.replace(R.id.container, Frag);
with
transaction.replace(R.id.content_frame, Frag);
I had this overlapping issue once due to android.R.id.content and i replaced it with R.id.content_frame which solved my issue.
But i see in your code that you have used a different container view ID, but this should work though.