i have used navigation drawable from android studio 2.2.3 with fragments as frag1,frag2
I want to send selected spinner values to all fragments,
i have managed to send first selected spinner item to all fragments using bundle but when i select the second item from spinner item list
nothing work,here is my codes
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
String data1;
#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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
#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);
ArrayList<String> list = new ArrayList<String>();
list.add("Top News");
list.add("Politics");
list.add("Business");
list.add("Sports");
list.add("Movies");
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list));
data1=spinner.getSelectedItem().toString();
Toast.makeText(MainActivity.this, spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
switch (itemId) {
case R.id.nav_menu1:
fragment = new frag1();
break;
case R.id.nav_menu2:
fragment = new frag2();
Bundle data2 = new Bundle();
data2.putString("data", data1);
fragment.setArguments(data2);
break;
case R.id.nav_menu3:
fragment = new frag3();
Bundle data = new Bundle();
data.putString("data", data1);
fragment.setArguments(data);
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
public class frag2 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_3, container, false);
TextView text = (TextView) view.findViewById(R.id.textView3);
String getArgument = getArguments().getString("data");
text.setText(getArgument);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu 1");
}
}
So where and how can i modify or my codes so that
1.i can send the selected spinner item to all fragments ?
2.i can retain the state of selected spinner value when navigate between fragments ?
Use onItemSelected listener and perform operation you want to perform there
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Related
I have one activity that uses two fragments, MainFragment and DetailFragment. The MainFragment has an expandable list view that has company names as groups and location names as children. When the user selects a category from the navigation drawer it updates the data in the adapter and updates the expandable list, displaying the correct companies.
When the user selects a location it opens the DetailFragment with information about that location and employees. The problem I'm having is when I step back. When I hit the back button it resets to the default category, and I've figured out that it's because it's calling the onViewCreated() method again, which is where I set up my views and adapter. The strange thing is, it remembers what list items were expanded, by index. So if I had the third item expanded in a different category, the third item in the default category is still expanded.
What I'd like to know is, how can I have it maintain the setup I had when I press back?
My MainFragment
public class MainFragment extends Fragment implements ExpandableListView.OnChildClickListener, NavigationSelectedListener {
private CompaniesExpandableListAdapter adapter;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
connectViews(view);
}
private void connectViews(View view) {
final ExpandableListView companyListView = (ExpandableListView) view.findViewById(R.id.companyListView);
final Navigation navigationItem = ((MainActivity) getActivity()).getNavigationItems().first();
getActivity().setTitle(navigationItem.getTitle());
adapter = new CompaniesExpandableListAdapter(navigationItem.getCompanies());
companyListView.setAdapter(adapter);
companyListView.setOnChildClickListener(this);
}
// ExpandableListView.OnChildClickListener
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
final DetailFragment detailFragment = new DetailFragment();
final Bundle args = new Bundle();
args.putInt(getString(R.string.extra_location_key), ((Locations) adapter.getChild(groupPosition, childPosition)).getPrimaryKey());
detailFragment.setArguments(args);
getFragmentManager()
.beginTransaction()
.replace(R.id.contentFrame, detailFragment, getString(R.string.tag_fragment_detail))
.addToBackStack(null)
.commit();
return false;
}
// NavigationSelectedListener
#Override
public void onNavigationItemSelected(Navigation navigationItem) {
// Go back to the main fragment.
getFragmentManager().popBackStack(getString(R.string.tag_fragment_main), FragmentManager.POP_BACK_STACK_INCLUSIVE);
// Send the selected item to the adapter.
adapter.updateData(navigationItem.getCompanies());
getActivity().setTitle(navigationItem.getTitle());
}
}
And my MainActivity
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private NavigationSelectedListener navigationCallback;
private DrawerLayout drawerLayout;
private RealmResults<Navigation> navigationItems;
private MainFragment mainFragment = new MainFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildNavigationDrawer();
connectViews();
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) drawerLayout.closeDrawer(GravityCompat.START);
else super.onBackPressed();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
navigationCallback.onNavigationItemSelected(navigationItems.get(item.getItemId()));
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
private void connectViews() {
navigationCallback = mainFragment;
getFragmentManager()
.beginTransaction()
.replace(R.id.contentFrame, mainFragment, getString(R.string.tag_fragment_main))
.commit();
}
private void buildNavigationDrawer() {
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerStateChanged(int newState) {
super.onDrawerStateChanged(newState);
// Hides the device keyboard when the navigation drawer is opened.
if (getCurrentFocus() != null) ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
};
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
fillNavigationDrawer();
}
public RealmResults<Navigation> getNavigationItems() {
return navigationItems;
}
}
You should use add instead of replace in your transaction.
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 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);
}
I have a Main Drawer activity which loads my fragments when a drawer item is selected. The fragment that is laoded contains a tabhost which hosts multiple fragments so you can switch to via tabs.
Before Tabs I had a fragment with a bunch of butons that when clicked, replaced the current fragment with a new fragment. The fragments all have listviews in them, and when you click an item replaced the current listview fragment with another fragment.
My problem is when I placed all my fragments into a tabhost the ArticleOnSelected no longer works, and force closes my app when ever an item is actually selected form the list view. Here is an example of one of the FC errors:
03-02 16:40:34.121 9066-9066/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalArgumentException: No view found for id 0x7f09008c (com.beerportfolio.beerportfoliopro:id/main) for fragment BreweryPage2{41ba3478 #2 id=0x7f09008c}
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:919)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
I see the problem is with the view, and I think it can not access the main framelayout from the layout which holds all the fragments with the navigation drawer.
My MainDrawer2 class is what opens first and is where the drawer and fragments are loaded into. The code is:
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
if(navItem == mCurrentNavItem){
return;
}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
The default fragment which is loaded is the fragment which holds my tabhost and creates the tabs:
public class StatisticsTab extends Fragment {
private FragmentTabHost mTabHost;
//Mandatory Constructor
public StatisticsTab() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabs,container, false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("Basic").setIndicator("Basic"),
StatisticsPage.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Brewery").setIndicator("Brewery"),
BreweryStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Style").setIndicator("Style"),
StyleStatistics.class, null);
mTabHost.addTab(mTabHost.newTabSpec("Taste").setIndicator("Taste"),
TasteStatisticsPage.class, null);
return rootView;
}
}
If I click on an item in my tab and bring up the listview like this:
It gives me the FC I posted above. The code for this fragment is:
public class BreweryStatistics extends Fragment implements GetBreweryStatisticsJSON.OnArticleSelectedListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.brewery_statistics_layout, container, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String url = "myURL";
//async task to get beer taste tag percents
GetBreweryStatisticsJSON task = new GetBreweryStatisticsJSON(getActivity());
task.setOnArticleSelectedListener(this);
task.execute(url);
// Inflate the layout for this fragment
return v;
}
#Override
public void onArticleSelected(String bID){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new BreweryPage2();
final Bundle bundle = new Bundle();
bundle.putString("breweryIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
And when that onArticleSelected above is executed it does not load the new fragment. In theory what should happen the Fragment that holds the tabhost StatisticsTab should be replaced with the new Fragment in the OnArticleSelected