I am using navigation drawer which calls multiple fragments on the click of a list item of navigation drawer.
In my scenario, parent activity handles 2 fragments. There is an expected behavior that I am facing in handling these fragments.
Here is what I am doing:
Go to offline mode -> Go to fragment 2 -> Minimize the app -> Go to online mode ( switch on the internet ) - > Resume the app
On resume of the app, the parent activity is called and in parent activity, by default fragment 1 is opened, rather it should open fragment 2.
Help is appreciated.
Here is my navigation drawer code -
public class NavigationDrawer extends ActionBarActivity implements OnItemClickListener {
private ActionBar actionBar;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
RelativeLayout user_panel;
LinearLayout mylinearlayout;
private ActionBarDrawerToggle mDrawerToggle;
// Initialize SharedPreferences and editor variable's.
SharedPreferences.Editor editor;
SharedPreferences pref;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
// Initialize SharedPreferences mode
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
username = pref.getString("name", null); // getting String
moveDrawerToTop();
initActionBar();
initDrawer();
//Quick cheat: Add Fragment 1 to default view
onItemClick(null, null, 0, 0);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
private void moveDrawerToTop() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
DrawerLayout drawer = (DrawerLayout) inflater.inflate(R.layout.decor, null); // "null" is important.
// HACK: "steal" the first child of decor view
ViewGroup decor = (ViewGroup) getWindow().getDecorView();
View child = decor.getChildAt(0);
decor.removeView(child);
LinearLayout container = (LinearLayout) drawer.findViewById(R.id.drawer_content); // This is the container we defined just now.
container.addView(child, 0);
drawer.findViewById(R.id.drawer).setPadding(0, getStatusBarHeight(), 0, 0);
ImageView profile = (ImageView) drawer.findViewById(R.id.image_view);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// Make the drawer replace the first child
decor.addView(drawer);
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
private int getContentIdResource() {
return getResources().getIdentifier("content", "id", "android");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
mDrawerToggle.syncState();
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == R.id.notification) {
Intent display_notify = new Intent(getApplicationContext(), DisplayActivity.class);
startActivity(display_notify);
return true;
}
return super.onOptionsItemSelected(item);
}
private void initActionBar() {
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
private void initDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mylinearlayout = (LinearLayout) findViewById(R.id.drawer);
mDrawerLayout.setDrawerListener(createDrawerToggle());
mDrawerList = (ListView) findViewById(R.id.MyList);
user_panel = (RelativeLayout) findViewById(R.id.user_profile_panel);
user_panel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
TextView user_name = (TextView) findViewById(R.id.left_panel_user_name);
user_name.setText(username);
ListAdapter adapter = (ListAdapter) (new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.nav_items)));
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(this);
}
private DrawerListener createDrawerToggle() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerStateChanged(int state) {
}
};
return mDrawerToggle;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDrawerLayout.closeDrawer(mylinearlayout);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ftx = fragmentManager.beginTransaction();
if (position == 0) {
ftx.replace(R.id.main_content, new FragmentOne());
} else if (position == 1) {
ftx.replace(R.id.main_content, new FragmentSecond());
} else if (position == 2) {
} else if (position == 3) {
} else if (position == 4) {
invitation();
} else if (position == 5) {
launchMarket();
} else if (position == 6) {
ftx.replace(R.id.main_content, new Setting_Fragment());
}
ftx.commit();
}
}
Related
How I go to the previous fragment when I click on back button.
RecyclerAdapter_1_ten.java
public class RecyclerAdapter_1_ten extends RecyclerView.Adapter<RecyclerAdapter_1_ten.ViewHolder> {
private String[] SubTxt = {"NCERT Solution",
"Notes"};
private int[] SubImage = {R.drawable.ic_answers_black_48dp,
R.drawable.ic_notes_black_48dp};
Activity activity;
public RecyclerAdapter_1_ten(Activity activity) {
this.activity = activity;
}
class ViewHolder extends RecyclerView.ViewHolder {
public int currentItem;
public ImageView itemImage;
public TextView itemTitle;
public ViewHolder(View itemView) {
super(itemView);
itemImage = (ImageView) itemView.findViewById(R.id.SubImage);
itemTitle = (TextView) itemView.findViewById(R.id.SubTxt);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
switch (position) {
case 0:
android.app.FragmentManager fm = activity.getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new SecondClass_10()).commit();
case 1:
Snackbar.make(v, "Comming Soon " + position,
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
});
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recycler_1_9, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
viewHolder.itemTitle.setText(SubTxt[i]);
viewHolder.itemImage.setImageResource(SubImage[i]);
}
#Override
public int getItemCount() {
return SubTxt.length;
}
}
SecondClass_10.java
public class SecondClass_10 extends Fragment {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
View rootview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.second_class_10, container, false);
recyclerView = (RecyclerView) rootview.findViewById(R.id.recycler_ten_page_second);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerAdapter_2_ten();
recyclerView.setAdapter(adapter);
return rootview;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
android.app.FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new FirstClass_9()).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
android.app.FragmentManager fn = getFragmentManager();
int id = item.getItemId();
if (id == R.id.nav_9) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_9()).commit();
} else if (id == R.id.nav_10) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_10()).commit();
} else if (id == R.id.nav_11) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_11()).commit();
} else if (id == R.id.nav_12) {
fn.beginTransaction().replace(R.id.content_frame, new FirstClass_12()).commit();
} else if (id == R.id.nav_aboutUs) {
} else if (id == R.id.nav_feedback) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
I follow many Tutorial but I didn't get solution Hope I'll get answer here. I have added recyclerview when I click on it it open fragment but when I click on back button instead of going back it goes to first Page.
How to go back to Fragment from Fragment when I click on Back button?
You can use Stack for holding the fragment instances. When you move to the next fragment push the fragment into the stack and detach it from your activity and in the onbackpressed event pop the fragment and attach it to the activity.
This is one of the best explanation that i came across when i started in SO for fragment navigation i hope it helps clear your understanding of how they work.
Android fragments navigation and backstack
There is some information that I want to display in the NavigationDrawer. This information is entered by the user in a previous activity. I use an intent to send the information to the Main Activity for the Drawer.
MainActivity (After user entered details)
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);
Intent intent = getIntent();
String info = intent.getStringExtra("info");
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.nav_item_dashboard);
break;
......
}
I have a specific layout for the navigation drawer and it contains a textview which I want to update with the String test. This is the fragment code and the xml for it.
FragmentDrawer Class
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(icons.getResourceId(i,-1));
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);
icons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
}
#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);
TextView userID = (TextView) layout.findViewById(R.id.nav_title_user);
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();
}
});
}
FramgentDrawer.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">
......
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceInverse"
android:text="#string/welcome_user"
android:id="#+id/nav_title_user"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"/>
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_below="#id/nav_header_container" />
I have managed to update the list in the drawer with Icons, Labels and a Header. I have done so by using a RecyclerViewAdapter.
The problem that I am having is that these details were from the resources (strings.xml).
How can I update a textview on a NavigationFragment when it has been created? How can I send a value to the fragment so that it will be used during OnCreateView of the fragment?
I was looking too much into it. The solution was quite simple...Even though it took me 3 hrs to figure this out :/
In the NavigationFragment, I created a method to update a textview with a string. In the MainActivity where I get the information from the intent, I just called the method like this:
drawerFragment.setUserTextView(info);
This is why taking breaks are important... ^^
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);
}
So i have A navigation Drawer in the MainActivity and when a child of the expandable List View is being clicked the content is presented in a fragment.
Inside the fragment i have a Menu icon , when clicked a search textbox is being displayed and the soft input Keyboard. but if someone push the toggle button to open the navigation drawer the soft input keyboard doesn't disappear. I have tried this methods :
First method: closing keyboard from MainActivity from onDrawerClosed ,using this code, nothing happened :
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Second method : closing the Keyboard from MainActivity from the method onOptionsItemSelected(MenuItem item) , getting the item id and writing the same code as previous in the case : android.R.id.home, nothing happened
Third method : As the previous method but within the Fragment writing the above code, nothing happened :
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Service.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
The soft Input Keyboard opens from the Fragment so i can't use something like the code in the above line because the ed_search is declared in the Fragment.
This is the code from the Main Activity:
public class MainActivity extends AppCompatActivity {
private static DrawerLayout mDrawerLayout;
private static ExpandableListView mExpandableListView;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private Toolbar mToolbar;
//nav drawer Title
private CharSequence mDrawerTitle;
//used to store app titles
private String mTitles;
//slide menu items
private String[] navMenuItems;
private String[] navSubMenuItems;
private TypedArray navMenuIcons;
private String[] navMenuLinks;
private List<NavDrawerItem> groupList;
private List<NavDrawerItem> childList;
private Map<NavDrawerItem, List<NavDrawerItem>> mapList;
private ExpandableListViewAdapter mAdapter;
//Fragment
private FragmentManager lFragmentManager;
private Fragment lFragment;
private static final NavDrawerItem firstItem = new NavDrawerItem("Latest",
"http://thegadgetflow.com/?feed=full_feed&paged=%d");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* Toolbar customization
*/
mToolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mTitles = firstItem.getTitle(); //setting the title of the first item
getSupportActionBar().setTitle(" Home");// changing the title of the action bar with the name of the item
/**
* Home screen
*/
lFragmentManager = getFragmentManager();
lFragment = lFragmentManager.findFragmentById(R.id.frame_container);
lFragment = new FragmentListItemHome();
Bundle mBundle = new Bundle();
mBundle.putSerializable("Item", firstItem);
lFragment.setArguments(mBundle);
//To the fragment
lFragmentManager.beginTransaction().replace(R.id.frame_container ,lFragment ).commit();
//navigation Drawer
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
//populate the expandable List view
createGroupList();
CreateChildList();
//put a reference to the expandable List view
mExpandableListView = (ExpandableListView)findViewById(R.id.list_slideMenu);
/**
* changing the groupIndicator from left to right
*/
mExpandableListView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
mExpandableListView.removeOnLayoutChangeListener(this);
//getting the width of the Expandable List view
int width = mExpandableListView.getWidth();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
mExpandableListView.setIndicatorBounds(width - getDipsFromPixel(35), width
- getDipsFromPixel(5));
} else {
mExpandableListView.setIndicatorBoundsRelative(width - getDipsFromPixel(35), width
- getDipsFromPixel(5));
}
}
});
// A new adapter
mAdapter = new ExpandableListViewAdapter(this, mapList, groupList);
//setting the adapter
mExpandableListView.setAdapter(mAdapter);
/**
* when a child of the Expandable list view is clicked
*/
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
final NavDrawerItem lItem = (NavDrawerItem) mAdapter.getChild(
groupPosition, childPosition);
mTitles = lItem.getTitle();
/**
* A new fragment
*/
boolean close = openListFragment(lItem);
//closing the navigation drawer
if (close) {
mDrawerLayout.closeDrawer(mExpandableListView);
//changing the title of the action bar with the title of the ChildItem
mToolbar.setTitle(" " + lItem.getTitle());
}
return true;
}
});
/**
* toggling the sliding menu
*/
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, mToolbar,
R.string.app_name, R.string.app_name) {
#Override
public void onDrawerClosed(View drawerView) {
mToolbar.setTitle(" " + mTitles);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
mToolbar.setTitle(" Sidebar");
invalidateOptionsMenu();
}
};
mActionBarDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_drawer);
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
//changing the ScrimColor
mDrawerLayout.setScrimColor(getResources().getColor(R.color.ColorPrimary));
CommonUtils.setContext(getApplicationContext());
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mExpandableListView);
//hiding the menu items of the action bar if the navigation drawer is open
if(mDrawerLayout!=null && drawerOpen)
menu.clear();
return super.onPrepareOptionsMenu(menu);
}
#Override
public void setTitle(CharSequence title) {
mTitles = (String)title;
mToolbar.setTitle(" Latest");
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurSationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.findItem(R.id.action_search).setVisible(false);
menu.findItem(R.id.action_share).setVisible(false);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
//not working
switch (item.getItemId()){
case android.R.id.home:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* changing the title inside a fragment
* #param title
*/
public void setActionBarTitle(String title) {
mToolbar.setTitle(title);
}
#Override
protected void onResume()
{
CommonUtils.resetBackButton();
super.onResume();
}
And this is the code from the Fragment :
public class FragmentListItemHome extends Fragment {
RelativeLayout rl_row_progress_bar;
LinearLayout ln_search;
EditText ed_search;
private RecyclerView mRecyclerView;
private ArrayList<GadgetItem> mList;
private AdapterListItemHome mAdapter;
private GridLayoutManager mLayoutManager;
private String mUrl;
private String mTitleGadget;
private View v;
private ImageButton mImageButton;
int loadedPage;
NavDrawerItem mData;
String searchText;
boolean isSearchMode;
int maxScrolledPage = 0;
boolean preloadingCancelled;
int spanSize = 2;
int pauseCounter = 0;
InputMethodManager inputMethod;
//paging
Map<Integer, Boolean> _loadingPages = new HashMap<Integer, Boolean>();
Map<Integer, Integer> _pageIndexes = new HashMap<Integer, Integer>();
private Toolbar mToolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadedPage = 1;
/**
* Toolbar customization
*/
savedInstanceState = getArguments();
if (savedInstanceState != null) {
mData = (NavDrawerItem) savedInstanceState.getSerializable("Item");
}
isSearchMode = false;
//for the search button in the action bar
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent , Bundle savedInstanceState) {
if(parent == null)
return null;
if(v != null)
return v;
//initialize the view v
v = inflater.inflate(R.layout.fragment_list_item_home, parent , false);
//initialization Recycler view
v.findViewById(R.id.rl_row_progress_bar_home); //the progress bar
//search items
mImageButton =(ImageButton)v.findViewById(R.id.anchor_home); //anchor
ln_search = (LinearLayout) v.findViewById(R.id.ln_search_home); // the layout for searching
ed_search = (EditText) v.findViewById(R.id.ed_search_home); // the text box for searching
ed_search.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
/**
* Overriding the soft keyboard for the search text box
*/
ed_search.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int Keycode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (Keycode == KeyEvent.KEYCODE_SEARCH) || (Keycode == KeyEvent.KEYCODE_ENTER)) {
inputMethod = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethod.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
String key = ed_search.getText().toString();
if (key != null && !key.isEmpty()) {
searchData(key);
}
}
return false;
}
});
/**
* Scrolling
*/
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
//getting the last visible position of the list
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//when scrolling hide keyboard and search box
ln_search.setVisibility(View.GONE);
showKeyboard(false);
int firstVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
if (newState == recyclerView.SCROLL_STATE_IDLE) {
//Log.d("bill",String.valueOf(lastPosition));
int onScrollingPage = getOnScrollingPage(firstVisibleItems);
if (maxScrolledPage <= onScrollingPage)
maxScrolledPage = onScrollingPage;
//int myPosition = layoutManager.getPosition();
//hiding the anchor when the lastPosition is 0
if (firstVisibleItems == 0)
mImageButton.setVisibility(View.GONE);
loadPage(onScrollingPage + 1);
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int firstVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
if (mLayoutManager != null && mLayoutManager.getItemCount() < 5) {
return;
} else {
changeFooterState(true);
}
int visibleItemCount = mLayoutManager.getChildCount();
int totalItemCount = mLayoutManager.getItemCount();
int pastVisiblesItems = firstVisibleItems;
// Log.d("bill","visibleItemCount: "+String.valueOf(visibleItemCount)+
// "totalItemCount: "+String.valueOf(totalItemCount)+"firstVisibleItem: "+String.valueOf(pastVisiblesItems));
if (pastVisiblesItems + visibleItemCount == totalItemCount && (mList != null && totalItemCount == mList.size())
&& totalItemCount != 0) {
changeFooterState(false);
} else {
changeFooterState(true);
}
}
});
}
/**
* searching
*/
public void searchData(String searchKey) {
loadedPage = 1;
_loadingPages.clear(); // clear the hash map
_pageIndexes.clear();
isSearchMode = true;
this.searchText = searchKey;
if(mList != null && mAdapter != null) {
mList.clear(); // clear the list
mAdapter.notifyDataSetChanged();
}
// Set title bar
((MainActivity) getActivity())
.setActionBarTitle(searchKey);
CommonUtils.showDialog(getActivity(), "Searching...", false);
getGadget(searchKey);
}
/**
*
* #param menu
* #param inflater
*/
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//the button search is setting to visible
menu.findItem(R.id.action_search).setVisible(true);
menu.findItem(R.id.action_share).setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_search:
isSearchMode = true;
//Log.d("billy","inside action_search");
rightHeaderButtonClick();
return true;
//how working
case R.id.action_share:
return false;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* showing the text box
*/
public void rightHeaderButtonClick() {
if (ln_search.isShown()) {
ln_search.setVisibility(View.GONE);
showKeyboard(false);
} else {
ln_search.setVisibility(View.VISIBLE);
ed_search.requestFocus();
showKeyboard(true);
//Log.d("bill", "rightHeaderButtonClick - open ln_search");
}
}
/**
* showing the keyboard
* #param isShow
*/
public void showKeyboard(boolean isShow) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Service.INPUT_METHOD_SERVICE);
if (isShow) {
// show keyboard
imm.showSoftInput(ed_search, 0);
} else {
// hide keyboard
imm.hideSoftInputFromWindow(ed_search.getWindowToken(), 0);
}
}
Thanks in advance!
use this
public static void showKeyboard(Activity pActivity, View pView) {
if (pView == null) {
pView = pActivity.getWindow().getCurrentFocus();
} else {
/**
* For {#link EditText}, a call to {#link View#requestFocus()} will
* open the keyboard as per inputType set for {#link EditText}
*/
pView.requestFocus();
}
if (pView != null) {
InputMethodManager imm = (InputMethodManager) pActivity
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(pView, InputMethodManager.SHOW_FORCED);
}
}
}
public static void hideKeyboard(View pView, Activity pActivity) {
if (pView == null) {
pView = pActivity.getWindow().getCurrentFocus();
}
if (pView != null) {
InputMethodManager imm = (InputMethodManager) pActivity
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(pView.getWindowToken(), 0);
}
}
}
I had a similar situation wherein I had search in the child fragment of the navigation drawer.
Now on searching the keyboard would pop up and when I wanted to click on the navigation drawer again the keyboard wouldn't hide so I mixed up the 2 solution above and came up with this.
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset){
hideKeyboard(true, ActivityName);
}
};
public static void hideKeyboard(boolean val, Activity activity) {
View view;
view = activity.getWindow().getCurrentFocus();
if (val == true) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
and guess what this worked! thanks for your help!
I want to implement Left & Right Side Slider Menu so I have set Right Side Slider in NavigationDrawerSlider which already have Left Side Slider by Default.
I am using ActionBarSherLock for this to support Application from Api 8. Slider is working fine but issue is that ActionBar is not showing Title.
Please help me to solve this issue. One more thing, When I Click on ImageView, It also fires ActionBarDrawerToggle. So, how to prevent this also ?
My Code:
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList_Left;
private ListView mDrawerList_Right;
private ActionBarDrawerToggle mDrawerToggle;
private ActionBar actionBar_Right;
private ArrayList<NavDrawerItem> navDrawerItems_Left;
private ArrayList<NavDrawerItem> navDrawerItems_Right;
private CharSequence mDrawerTitle_Left;
private CharSequence mTitle_Left;
private CharSequence mDrawerTitle_Right;
private CharSequence mTitle_Right;
private String[] mFragmentTitles_Left;
private String[] mFragmentTitles_Right;
private TypedArray navMenuIcons_Left;
private TypedArray navMenuIcons_Right;
private NavDrawerListAdapter adapter_Left;
private NavDrawerListAdapter adapter_Right;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle_Left = mDrawerTitle_Left = getTitle();
mFragmentTitles_Left = getResources().getStringArray(
R.array.nav_drawer_items);
mFragmentTitles_Right = getResources().getStringArray(
R.array.nav_drawer_items_right);
navMenuIcons_Left = getResources().obtainTypedArray(
R.array.nav_drawer_icons);
navMenuIcons_Right = getResources().obtainTypedArray(
R.array.nav_drawer_icons_right);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList_Left = (ListView) findViewById(R.id.list_left_slidermenu);
mDrawerList_Right = (ListView) findViewById(R.id.list_right_slidermenu);
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
navDrawerItems_Left = new ArrayList<NavDrawerItem>();
navDrawerItems_Right = new ArrayList<NavDrawerItem>();
// Left Side Menus...
// Home...
navDrawerItems_Left.add(new NavDrawerItem(mFragmentTitles_Left[0],
navMenuIcons_Left.getResourceId(0, -1)));
navMenuIcons_Left.recycle();
// Right Side Menus...
// Edit Profile...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[0],
navMenuIcons_Right.getResourceId(0, -1)));
// Change Password...
navDrawerItems_Right.add(new NavDrawerItem(mFragmentTitles_Right[1],
navMenuIcons_Right.getResourceId(1, -1)));
navMenuIcons_Right.recycle();
mDrawerList_Left
.setOnItemClickListener(new DrawerItemClickListener_Left());
mDrawerList_Right
.setOnItemClickListener(new DrawerItemClickListener_Right());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
adapter_Left = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Left);
mDrawerList_Left.setAdapter(adapter_Left);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name);
adapter_Right = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems_Right);
mDrawerList_Right.setAdapter(adapter_Right);
ImageView imgRight = (ImageView) findViewById(R.id.imgRightMenu);
imgRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (mDrawerLayout.isDrawerOpen(mDrawerList_Right)) {
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mTitle_Right);
} else {
mDrawerLayout.openDrawer(mDrawerList_Right);
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mDrawerTitle_Right);
}
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem_Left(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList_Left)) {
mDrawerLayout.closeDrawer(mDrawerList_Left);
setTitle(mTitle_Left);
} else {
mDrawerLayout.openDrawer(mDrawerList_Left);
mDrawerLayout.closeDrawer(mDrawerList_Right);
setTitle(mDrawerTitle_Left);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener_Left implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Left(position);
}
}
private void selectItem_Left(int position) {
Fragment newFragment = new Home();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new Home();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Left.setItemChecked(position, true);
setTitle(mFragmentTitles_Left[position]);
mDrawerLayout.closeDrawer(mDrawerList_Left);
}
private class DrawerItemClickListener_Right implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem_Right(position);
}
}
private void selectItem_Right(int position) {
Fragment newFragment = new EditProfile();
FragmentManager fm = getSupportFragmentManager();
switch (position) {
case 0:
newFragment = new EditProfile();
break;
case 1:
newFragment = new ChangePassword();
break;
}
fm.beginTransaction().replace(R.id.frame_container, newFragment)
.commit();
mDrawerList_Right.setItemChecked(position, true);
setTitle(mFragmentTitles_Right[position]);
mDrawerLayout.closeDrawer(mDrawerList_Right);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
I have figured out that It is not showing title because of
actionBar_Right = getSupportActionBar();
actionBar_Right.setCustomView(R.layout.right_menu);
actionBar_Right.setDisplayShowTitleEnabled(true);
actionBar_Right.setDisplayShowCustomEnabled(true);
What to do for this ?
For showing the title in the ActionBar setTitle must be overridden:
#Override
public void setTitle(CharSequence title)
{
this.title = title;
getSupportActionBar().setTitle(title);
}