I am designing an android app and have created an activity which cannot extend to a fragment as I am using a gridview. The problem is, when I try to navigate to the activity within the navigational drawer it does not work. Is there a way I can extend to fragment while still using the gridview?
Activity I am trying to navigate to
public class GalleryActivity extends FragmentActivity {
private GridView gridView;
private GridViewAdapter gridAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_gallery);
gridView = (GridView) findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, getData());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(GalleryActivity.this, DetailsActivity.class);
intent.putExtra("title", item.getTitle());
intent.putExtra("image", item.getImage());
//Start details activity
startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
/**
* Prepare some dummy data for gridview
*/
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<>();
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
Below is the code for the navigational drawer, I am trying to navigate to GalleryActivity
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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);
}
//Function to switch screens by passing the navigation ID
private void displaySelectedScreen(int id) {
Fragment fragment = null;
switch (id) {
case R.id.nav_Home:
fragment = new HomeActivity();
break;
case R.id.nav_About:
fragment = new AboutActivity();
break;
case R.id.nav_Gallery:
fragment = new GalleryActivity();
break;
case R.id.nav_locationMap:
fragment = new LocationActivity();
break;
case R.id.nav_products:
fragment = new ProductsActivity();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_main, fragment);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
}
Refer to Android switch Fragments in the new design support navigation drawer
You need to set a setNavigationItemSelectedListener on the navigationView
you should cast the fragment activity to only fragment.like this use this code..
public class GalleryActivity extends Fragment {
private GridView gridView;
private GridViewAdapter gridAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, null);
gridView = (GridView) view.findViewById(R.id.gridView);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout, getData());
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(GalleryActivity.this, DetailsActivity.class);
intent.putExtra("title", item.getTitle());
intent.putExtra("image", item.getImage());
//Start details activity
startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_gallery, container, false);
}
}
First of all, how you imagined creating fragment by passing activity type?
Fragment fragment = null;
switch (id) {
case R.id.nav_Home:
fragment = new HomeActivity();
break;
Related
I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#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.page__navigation, 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.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}
The bottom line is, there is a main activity, and 4 fragments one of the fragments is something like settings.
In the markup of the fragment with the RadioGroup and 3 RadioButton settings, the positions of which must correspond to the starting fragment, ie the first, second or third. It is necessary to make sure that when the application is closed, the positions of the pressed RadioButtons are saved and the required fragment is displayed in accordance with the position.
Code activity
public class Main2Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
FragmentRoute froute;
FragmentSearch fSearch;
FragmentHelp fHelp;
FragmentSearchRoute fSearchRoute;
FragmentSettings fSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
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);
fSearch = new FragmentSearch ();
froute = new FragmentRoute();
fHelp = new FragmentHelp();
fSettings = new FragmentSettings();
fSearchRoute = new FragmentSearchRoute();
getFragmentManager().beginTransaction().replace(R.id.container, new FragmentRoute(), "test").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();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
int id = item.getItemId();
if (id == R.id.route) {
ft.replace(R.id.container, froute);
} else if (id == R.id.search) {
ft.replace(R.id.container, fSearch);
} else if (id == R.id.search_route) {
ft.replace(R.id.container, fSearchRoute);
} else if (id == R.id.settings) {
ft.replace(R.id.container, fSettings);
} else if (id == R.id.help) {
ft.replace(R.id.container, fHelp);
}ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Code Fragment-settings
public class FragmentSettings extends PreferenceFragment {
RadioGroup radioGroup;
SharedPreferences sharedPreferences;
RadioButton radioButton1,radioButton2,radioButton3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle(R.string.fr5);
View rv = inflater.inflate(R.layout.fragment_settings, container, false);
radioGroup = (RadioGroup) rv.findViewById(R.id.radioGroup);
radioButton1 = (RadioButton) rv.findViewById(R.id.radioButton1);
radioButton2 = (RadioButton) rv.findViewById(R.id.radioButton2);
radioButton3 = (RadioButton) rv.findViewById(R.id.radioButton3);
return rv;
}
}
1. Use SharedPreferences to store the selected RadioButton position.
public class FragmentSettings extends PreferenceFragment {
RadioGroup radioGroup;
RadioButton radioButton1,radioButton2,radioButton3;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle(R.string.fr5);
View rv = inflater.inflate(R.layout.fragment_settings, container, false);
radioGroup = (RadioGroup) rv.findViewById(R.id.radioGroup);
radioButton1 = (RadioButton) rv.findViewById(R.id.radioButton1);
radioButton2 = (RadioButton) rv.findViewById(R.id.radioButton2);
radioButton3 = (RadioButton) rv.findViewById(R.id.radioButton3);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
editor = sharedPreferences.edit();
// Required to get the checked RadioButton id
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int selectedPosition;
switch (checkedId) {
case R.id.radioButton1:
selectedPosition = 1;
break;
case R.id.radioButton2:
selectedPosition = 2;
break;
case R.id.radioButton3:
selectedPosition = 3;
break;
default:
selectedPosition = 1;
break;
}
// Store in SharedPreferences
editor.putInt("SELECTED_POSITION", selectedPosition);
editor.commit();
}
});
return rv;
}
}
2. In your Main2Activity, onCreate() method get SELECTED_POSITION value from SharedPreferences and show your desired Fragment.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
........
...............
fSearch = new FragmentSearch();
froute = new FragmentRoute();
fHelp = new FragmentHelp();
fSettings = new FragmentSettings();
fSearchRoute = new FragmentSearchRoute();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
int selectedPosition = sharedPreferences.getInt("SELECTED_POSITION", 1);
switch (selectedPosition) {
case 1:
// FragmentSearch
getFragmentManager().beginTransaction().replace(R.id.container, fSearch).commit();
break;
case 2:
// FragmentRoute
getFragmentManager().beginTransaction().replace(R.id.container, froute).commit();
break;
case 3:
// FragmentHelp
getFragmentManager().beginTransaction().replace(R.id.container, fHelp).commit();
break;
default:
getFragmentManager().beginTransaction().replace(R.id.container, fSearch).commit();
break;
}
}
Hope this will help~
I am having problems restoring the states of the different fragments in the NavigationDrawer activity. I have 4 tabs which calls 4 different fragments. When I switch back I want to restore the previous state. I have been trying but cannot seem to be able to implement addToBackStack when restoring states. The following code again reloads the fragments.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
homeFragment fragment=new homeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
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);
}
#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.
int id = item.getItemId();
if (id == R.id.nav_camera) {
homeFragment fragment=new homeFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.addToBackStack("home").commit();
} else if (id == R.id.nav_gallery) {
techNews fragment=new techNews();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.addToBackStack("tech").commit();
} else if (id == R.id.nav_slideshow) {
nepal fragment=new nepal();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_manage) {
mobilePrice fragment=new mobilePrice();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
homeFragment.java
public class homeFragment extends Fragment {
private RecyclerView rvItem;
private updateAdapter updateLatestPage;
public homeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main);
View rootview=inflater.inflate(R.layout.fragment_home,container,false);
rvItem = (RecyclerView)rootview.findViewById(R.id.rvItem);
rvItem.setHasFixedSize(true);
final LinearLayoutManager manager = new LinearLayoutManager(getContext());
rvItem.setLayoutManager(manager);
String url = "http://www.gadgetsinnepal.com.np/wp-json/wp/v2/posts/?page=";
updateLatestPage = new updateAdapter(rvItem, getContext(), url, manager);
updateLatestPage.fetchAndPut();
return rootview;
}
}
TechNews.java
public class techNews extends Fragment {
private RecyclerView rvItem;
private updateAdapter updateLatestPage;
public techNews() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setContentView(R.layout.activity_main);
View rootview=inflater.inflate(R.layout.fragment_home,container,false);
rvItem = (RecyclerView)rootview.findViewById(R.id.rvItem);
rvItem.setHasFixedSize(true);
final LinearLayoutManager manager = new LinearLayoutManager(getContext());
rvItem.setLayoutManager(manager);
String url = "http://www.gadgetsinnepal.com.np/wp-json/wp/v2/posts/?categories=1&&page=";
updateLatestPage = new updateAdapter(rvItem, getContext(), url, manager);
updateLatestPage.fetchAndPut();
return rootview;
}
}
All other fragments are similar. How do I go about restoring the states of each fragment?
I'm trying to add an button icon in the upper right hand side of action bar and I follow this tutorial
Claims1.java
public class Claims1 extends Fragment {
long fk;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
fk = bundle.getLong("ab");
View claims = inflater.inflate(R.layout.claims, container, false);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView imageView = new ImageView(actionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL);
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
actionBar.setCustomView(imageView);
return claims;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// get list items from strings.xml
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.nav_drawer_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.mipmap.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
)
{
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// 2.1 create ActionBarDrawerToggle
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[5];
drawerItem[0] = new ObjectDrawerItem(R.mipmap.timesheet, "Time Sheet");
drawerItem[1] = new ObjectDrawerItem(R.mipmap.claims, "Claims");
drawerItem[2] = new ObjectDrawerItem(R.mipmap.project_icon, "Project");
drawerItem[3] = new ObjectDrawerItem(R.mipmap.report, "Report");
drawerItem[4] = new ObjectDrawerItem(R.mipmap.view, "View");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment=new Information();
break;
case 1:
fragment=new Claims1();
Bundle bundle=new Bundle();
bundle.putLong("ab",WorkDetailsTable.ab);
fragment.setArguments(bundle);
break;
case 2:
fragment=new Project();
break;
case 3:
fragment=new Report();
break;
case 4:
fragment=new ViewView();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
However, my app crashed. Do I need to add anything in my claims1.xml?
11-15 13:22:27.384 4199-4199/com.example.project.project E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 4199
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.app.ActionBar.getDisplayOptions()' on a null object reference
at com.example.project.project.Claims1.onCreateView(Claims1.java:26)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
(Claims1.java:26)
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
You are using wrong getActionBar method.
You are using AppCompatActivity so action bar is from supported library.
You should use ((AppCompatActivity) getActivity()).getSupportActionBar();
If you not make cast getActionBaris asking about android.app.ActionBar
but using AppCompatActivity you need to ask about android.support.v7.app.ActionBar
Hi I want to change view with the drawer selection, it work but the first view stay under the new one...
I have a superimposition of layout...
What Should i do?
Also How can i recover the id of current layout?
public class display extends MainActivity {
private String[] drawerListViewItems;
private ListView drawerListView;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_launcher,
R.string.open,
R.string.close
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle SaveInstanceState) {
super.onPostCreate(SaveInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem target) {
if (actionBarDrawerToggle.onOptionsItemSelected(target)) {
return true;
}
return super.onOptionsItemSelected(target);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View v, int pos, long id) {
Toast.makeText(display.this, ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
selectItem(pos);
drawerLayout.closeDrawer(drawerListView);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
break;
case 1:
fragment = new test2();
break;
case 2:
fragment = new test3();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.drawer_layout, fragment).commit();
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
drawerLayout.closeDrawer(drawerListView);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
}
If the first view remains under the new one, maybe the xml file associated with the new fragment doesn't have a background defined and it might be transparent.
Try to define android:background in the root element of the new view.
For the fragment id question, I think it's not possible to recover the id. You could store it in a global variable, or you can use string tags in order to identify the fragments, like it's done here:
get the latest fragment in backstack