Tried many ways, but none works perfectly. I want to get main activity from the fragments set up in a navigation view.
I tried
#Override
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
but it won't function properly. I want it like when I'm in a fragmented activity it returns back to main and while clicking back again it quits (I already did this), help me out with when back pressed get back to main activity
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1000 ;
private static final String TAG = "MainActivity";
private AdView mAdView;
ImageView imageView;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
List<Item> items;
CustomAdapter adapter;
private long backpressedtime;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,"Permission Denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String str="Click on Wallpaper to set Wallpaper";
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
imageView=(ImageView)findViewById(R.id.imageView);
mDrawerLayout=(DrawerLayout) findViewById(R.id.dl);
mToggle=new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.Navigation_v);
setupDrawerContent(navigationView);
ActionBar actionBar = getSupportActionBar();
recyclerView =(RecyclerView)findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
imageView=(ImageView)findViewById(R.id.imageView);
initItem();
//start service and play music
startService(new Intent(MainActivity.this, SoundService.class));
}
public void toast(View v) {
Toast.makeText(MainActivity.this, "Wallpaper Set", Toast.LENGTH_LONG).show();
}
private void initItem() {
items = new ArrayList<>();
items.add(new Item(0,"Wide","https://images8.alphacoders.com/532/thumb-1920-532407.jpg"));
items.add(new Item(1, "Wide","https://images5.alphacoders.com/394/thumb-1920-394511.jpg"));
items.add(new Item(1,"Wide","https://images5.alphacoders.com/408/thumb-1920-408539.jpg"));
adapter = new CustomAdapter(this,items);
recyclerView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onDestroy() {
//stop service and stop music
stopService(new Intent(MainActivity.this, SoundService.class));
super.onDestroy();
}
public void selectItemDrawer(MenuItem menuItem){
Fragment myFragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.walkthrough:
fragmentClass = Walkthrough.class;
break;
case R.id.info:
fragmentClass = About.class;
break;
default:
fragmentClass = Walkthrough.class;
}
try {
myFragment = (Fragment) fragmentClass.newInstance();
}
catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return true;
}
});
}
#Override
public void onBackPressed() {
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Are you sure you want to exit?");
builder.setCancelable(true);
builder.setNegativeButton("No Stay ;-)", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.setPositiveButton("Yes :'-(", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
Walkthrough.java
public class Walkthrough extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Walkthrough() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Walkthrough.
*/
// TODO: Rename and change types and number of parameters
public static Walkthrough newInstance(String param1, String param2) {
Walkthrough fragment = new Walkthrough();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_walkthrough, container, false);
WebView webView = (WebView)v.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true); //enable javascript
webView.setWebViewClient(new WebViewClient()); //important to open url in your app
webView.loadUrl("http://ign.com/wikis/the-last-of-us/Prologue");
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
If you want to go back to the MainActivity onBack click of WalkthroughFragment then while commit your fragment add it to BackStack using this method:
FragmentTransaction addToBackStack (String name)
This method will do the below operation:
Will Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
You can use it like that
FragmentTransaction ftx = getFragmentManager().beginTransaction();
ftx.replace(R.id.my_container_frame, fragment);
ftx.addToBackStack(null);
ftx.commit();
Alternatively you include all the function invocations on a single line
getSupportFragmentManager().beginTransaction().replace('Your Fragment Container ID', new 'Fragment Class Name').addToBackStack(null).commit();
Cheers!
Related
I have 4 tabs in Fragment A.The first tab has a listview. I have attached a Navigation drawer switching between other 3 tabs, Fragment B, C and D. Now when I switch from Fragment A to Fragment B and back, the first tab doesn't show the listview. But when I switch from 3rd tab and come back to 1st tab it gets the listview data and loads it. What am I doing wrong? I have attached my MainActivity which has implemented navigation drawer and my HomeFragment which has four tabs.
MainActivity.java
public class MainActivity extends AppCompatActivity implements {
// index to identify current nav menu item
public static int navItemIndex = 0;
// tags used to attach the fragments
// toolbar titles respected to selected nav menu item
private String[] activityTitles;
// flag to load home fragment when user presses back key
private boolean shouldLoadHomeFragOnBackPress = true;
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase1 = FirebaseDatabase.getInstance().getReference();
mHandler = new Handler();
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fab = (FloatingActionButton) findViewById(R.id.fab);
// Navigation view header
// load toolbar titles from string resources
activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles);
// load nav menu header data
loadNavHeader();
// initializing navigation menu
setUpNavigationView();
if (savedInstanceState == null) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
}
/***
* Load navigation menu header information
* like background image, profile image
* name, website, notifications action view (dot)
*/
private void loadNavHeader() {
}
/***
* Returns respected fragment that user
* selected from navigation menu
*/
private void loadHomeFragment() {
// selecting appropriate nav menu item
selectNavMenu();
// set toolbar title
setToolbarTitle();
// if user select the current navigation menu again, don't do anything
// just close the navigation drawer
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawer.closeDrawers();
// show or hide the fab button
toggleFab();
return;
}
// Sometimes, when fragment has huge data, screen seems hanging
// when switching between navigation menus
// So using runnable, the fragment is loaded with cross fade effect
// This effect can be seen in GMail app
Runnable mPendingRunnable = new Runnable() {
#Override
public void run() {
// update the main content by replacing fragments
Fragment fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commitAllowingStateLoss();
}
};
// If mPendingRunnable is not null, then add to the message queue
if (mPendingRunnable != null) {
mHandler.post(mPendingRunnable);
}
// show or hide the fab button
toggleFab();
//Closing drawer on item click
drawer.closeDrawers();
// refresh toolbar menu
invalidateOptionsMenu();
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
// home
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
case 1:
case 2:
case 3:
case 4:
default:
return new HomeFragment();
}
}
private void setToolbarTitle() {
getSupportActionBar().setTitle(activityTitles[navItemIndex]);
}
private void selectNavMenu() {
navigationView.getMenu().getItem(navItemIndex).setChecked(true);
}
private void setUpNavigationView() {
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.nav_home:
navItemIndex = 0;
break;
case R.id.nav_live:
navItemIndex = 1;
break;
case R.id.nav_edit:
navItemIndex = 2;
break;
case R.id.nav_competitions:
navItemIndex = 3;
break;
case R.id.nav_settings:
navItemIndex = 4;
break;
case R.id.nav_about_us:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, CompetitionActivity.class));
drawer.closeDrawers();
return true;
case R.id.nav_report_bug:
// launch new intent instead of loading fragment
startActivity(new Intent(MainActivity.this, ReportBugActivity.class));
drawer.closeDrawers();
return true;
default:
navItemIndex = 0;
}
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawer.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessary or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadHomeFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex != 0) {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
return;
}
}
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure?")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}).setNegativeButton("no", null).show();
//System.exit(0);
//super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// show menu only when home fragment is selected
if (navItemIndex == 0) {
getMenuInflater().inflate(R.menu.main, menu);
}
// when fragment is notifications, load the menu created for notifications
if (navItemIndex == 3) {
getMenuInflater().inflate(R.menu.notifications, 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_logout) {
auth = FirebaseAuth.getInstance();
auth.signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
// show or hide the fab
private void toggleFab() {
if (navItemIndex == 0)
fab.show();
else
fab.hide();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private int dpToPx(int dp)
{
float density = getApplication().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
#Override
public void setActionBarTitle(String home) {
}`**
HomeFragment.java
public class HomeFragment extends android.support.v4.app.Fragment {
private AppCompatActivity aca=new AppCompatActivity();
//private class Act extends AppCompatActivity {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
//tabs
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_question_answer_black_24dp,
R.drawable.ic_notifications_black_24dp,
R.drawable.ic_people_black_24dp,
R.drawable.ic_face_black_24dp,
};
private OnFragmentInteractionListener mListener;
private LayoutInflater inflator;
public ViewGroup container;
private Bundle savedInstancesState;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment HomeFragment.
*/
// TODO: Rename and change types and number of parameters
public HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
public HomeFragment() {
// Required empty public constructor
}
LayoutInflater inflater;
#Override
public void onCreate(Bundle savedInstanceState) {
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context=getContext();
inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View v=inflater.inflate(R.layout.fragment_home, container, false);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
//viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
tabLayout = (TabLayout) v.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
return v;
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
ColorStateList colors;
colors = getResources().getColorStateList(R.color.tab_icon);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
Drawable icon = tab.getIcon();
if (icon != null) {
icon = DrawableCompat.wrap(icon);
DrawableCompat.setTintList(icon, colors);
}
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onDestroyView(){
super.onDestroyView();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter((getActivity()).getSupportFragmentManager());
adapter.addFrag();
adapter.addFrag();
adapter.addFrag();
adapter.addFrag();
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<android.support.v4.app.Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
//return mFragmentTitleList.get(position);
return null;
}
}
public void setActionBarTitle(String title) {
aca.getSupportActionBar().setTitle(title);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
void setActionBarTitle(String home);
}
}
I'm new in android programmation. I'm triyng to implement a navigation drawer in wordpress reader declan gao project. I'm getting crazy. He loads a list of wordpress posts and display it with cardview. If I put all necessary in activity_main My navigation drawer appears below cardview posts and I can't interact with it. If I try to put it in TabLayoutFragment i have a lot of errors!!!
Is there someone who can help me to insert navigation drawer in the right place!!!
Than you so much!!!
This is MainActivity.java
public class MainActivity extends AppCompatActivity implements
RecyclerViewFragment.PostListListener, PostFragment.PostListener,
TabLayoutFragment.TabLayoutListener, SearchResultFragment.SearchResultListener
{
private static final String TAG = MainActivity.class.getSimpleName();
public static final String TAB_LAYOUT_FRAGMENT_TAG = "TabLayoutFragment";
public static final String POST_FRAGMENT_TAG = "PostFragment";
private FragmentManager fm = null;
private TabLayoutFragment tlf;
private PostFragment pf;
private SearchResultFragment srf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
fm = getSupportFragmentManager();
// Setup fragments
tlf = new TabLayoutFragment();
pf = new PostFragment();
srf = new SearchResultFragment();
FragmentTransaction ft = fm.beginTransaction();
ft.add(android.R.id.content, pf, POST_FRAGMENT_TAG);
ft.add(android.R.id.content, tlf, TAB_LAYOUT_FRAGMENT_TAG);
ft.hide(pf);
ft.commit();
}
/**
* Invoked when a post in the list is selected
*
* #param post Selected Post object
*/
#Override
public void onPostSelected(Post post, boolean isSearch) {
// Find the fragment in order to set it up later
pf = (PostFragment) getSupportFragmentManager().findFragmentByTag(POST_FRAGMENT_TAG);
// Set necessary arguments
Bundle args = new Bundle();
args.putInt("id", post.getId());
args.putString("title", post.getTitle());
args.putString("date", post.getDate());
args.putString("author", post.getAuthor());
args.putString("content", post.getContent());
args.putString("url", post.getUrl());
//args.putString("thumbnailUrl", post.getThumbnailUrl());
args.putString("featuredImage", post.getFeaturedImageUrl());
// Configure PostFragment to display the right post
pf.setUIArguments(args);
// Show the fragment
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
if (!isSearch) { // Hide TabLayoutFragment if this is not search result
ft.hide(tlf);
} else { // Otherwise, hide the search result, ie. SearchResultFragment.
ft.hide(srf);
}
ft.show(pf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Invoked when a search query is submitted
*
* #param query Selected Post object
*/
#Override
public void onSearchSubmitted(String query) {
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
// Send query to fragment using factory method
srf = SearchResultFragment.newInstance(query);
ft.add(android.R.id.content, srf);
ft.hide(tlf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Invoked when comment menu is selected
*
* #param id ID of the article, assigned by WordPress
*/
#Override
public void onCommentSelected(int id) {
Bundle args = new Bundle();
args.putInt("id", id);
// Setup CommentFragment to display the right comments page
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right,
android.R.anim.slide_in_left, android.R.anim.slide_out_right);
ft.hide(pf);
ft.addToBackStack(null);
ft.commit();
}
/**
* Intercept back button event, reset ActionBar if necessary
*/
#Override
public void onBackPressed() {
resetActionBarIfApplicable();
super.onBackPressed();
}
/**
* Simulate a back button press when home is selected
*/
#Override
public void onHomePressed() {
resetActionBarIfApplicable();
fm.popBackStack();
}
/**
* Reset TabLayoutFragment's ActionBar if necessary
*/
private void resetActionBarIfApplicable() {
Log.d(TAG, "SearchResultFragment is visible: " + srf.isHidden());
if (srf.isVisible()) {
tlf.resetActionBar();
}
}
// Commented out coz we will let fragments handle their own Options Menus
//#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;
//}
}
This is activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!--<android.support.v7.widget.Toolbar-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"-->
<!--android:background="#color/colorPrimary"-->
<!--android:theme="#style/ThemeOverlay.AppCompat.Dark"-->
<!--android:id="#+id/toolbar">-->
<!--</android.support.v7.widget.Toolbar>-->
<!--<FrameLayout-->
<!--android:id="#+id/container"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent">-->
<!--</FrameLayout>-->
This is TabLayoutFragment.java
/**
* Fragment to display TabLayout and ViewPager.
* Activities that contain this fragment must implement the
* {#link TabLayoutFragment.TabLayoutListener} interface
* to handle interaction events.
*/
public class TabLayoutFragment extends Fragment implements SearchView.OnQueryTextListener {
private static final String TAG = "TabLayoutFragment";
private ProgressDialog mProgressDialog;
private TabLayout mTabLayout;
private ViewPager mViewPager;
private Toolbar toolbar;
private SearchView searchView;
private MenuItem searchMenuItem;
// List of all categories
protected static ArrayList<Category> categories = null;
private TabLayoutListener mListener;
public TabLayoutFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Stops onDestroy() and onCreate() being called when the parent
// activity is destroyed/recreated on configuration change
setRetainInstance(true);
// Display a search menu
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_tab_layout, container, false);
toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((MainActivity)getActivity()).setSupportActionBar(toolbar);
mTabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
mViewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
// Preload 1 page to either side of the current page
mViewPager.setOffscreenPageLimit(1);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadCategories();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
Log.d(TAG, "onCreateOptionsMenu()");
inflater.inflate(R.menu.menu_main, menu);
// Create expandable & collapsible SearchView
SearchManager searchManager = (SearchManager)
getActivity().getSystemService(Context.SEARCH_SERVICE);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setIconifiedByDefault(false); // Expanded by default
//searchView.requestFocus();
searchView.setQueryHint(getString(R.string.search_hint));
searchView.setOnQueryTextListener(this);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_search) {
searchView.requestFocus();
}
return true;
}
/**
* Reset the ActionBar to show proper menu and collapse SearchView
*/
protected void resetActionBar() {
((MainActivity)getActivity()).setSupportActionBar(toolbar);
searchMenuItem.collapseActionView();
}
/**
* Download categories and create tabs
*/
private void loadCategories() {
// Display a progress dialog
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage(getString(R.string.loading_categories));
// User cannot dismiss it by touching outside the dialog
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
// Make a request to get categories
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Config.CATEGORY_URL,
null,
new Response.Listener<JSONObject>() {
// Request succeeded
#Override
public void onResponse(JSONObject jsonObject) {
mProgressDialog.dismiss();
// Get categories from JSON data
categories = JSONParser.parseCategories(jsonObject);
RecyclerViewFragmentPagerAdaptor adaptor = new
RecyclerViewFragmentPagerAdaptor(getChildFragmentManager(), categories);
mViewPager.setAdapter(adaptor);
mTabLayout.setupWithViewPager(mViewPager);
}
},
// Request failed
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "----- Volley Error -----");
mProgressDialog.dismiss();
// Show an INDEFINITE Snackbar. New in design support lib v22.2.1.
Snackbar.make(mTabLayout, R.string.error_load_categories,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.action_retry,
new View.OnClickListener() {
#Override
public void onClick(View v) {
loadCategories();
}
}).show();
}
});
// Add the request to request queue
AppController.getInstance().addToRequestQueue(request);
}
#Override
public boolean onQueryTextSubmit(String query) {
searchView.clearFocus(); // Hide soft keyboard
mListener.onSearchSubmitted(query); // Deal with fragment transaction on MainActivity
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (TabLayoutListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
"must implement PostListListener");
}
}
// Interface used to communicate with MainActivity
public interface TabLayoutListener {
void onSearchSubmitted(String query);
}
}
This is FragmentTabLayout.xml
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.declangao.wordpressreader.app.TabLayoutFragment">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|enterAlways"
/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"
style="#style/CustomTabLayout"/>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
This is RecyclerViewFragment.java
/**
* Fragment to display a RecyclerView.
* Activities that contain this fragment must implement the
* {#link RecyclerViewFragment.PostListListener} interface
* to handle interaction events.
*/
public class RecyclerViewFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = "RecyclerViewFragment";
protected static final String CAT_ID = "id";
protected static final String QUERY = "query";
private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;
private MyRecyclerViewAdaptor mAdaptor;
private LinearLayoutManager mLayoutManager;
// Widget to show user a loading message
private TextView mLoadingView;
// List of all posts in the ListView
private ArrayList<Post> postList = new ArrayList<>();
// A flag to keep track if the app is currently loading new posts
private boolean isLoading = false;
private int mPage = 1; // Page number
private int mCatId; // Category ID
private int mPreviousPostNum = 0; // Number of posts in the list
private int mPostNum; // Number of posts in the "new" list
private String mQuery = ""; // Query string used for search result
// Flag to determine if current fragment is used to show search result
private boolean isSearch = false;
// Keep track of the list items
private int mPastVisibleItems;
private int mVisibleItemCount;
private PostListListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param id ID of the category.
* #return A new instance of RecyclerViewFragment.
*/
public static RecyclerViewFragment newInstance(int id) {
RecyclerViewFragment fragment = new RecyclerViewFragment();
Bundle args = new Bundle();
args.putInt(CAT_ID, id);
fragment.setArguments(args);
return fragment;
}
/**
* Use this factory method to create a new instance of this fragment
* using the provided parameters to display search result.
*
* #param query search query.
* #return A new instance of RecyclerViewFragment.
*/
public static RecyclerViewFragment newInstance(String query) {
RecyclerViewFragment fragment = new RecyclerViewFragment();
Bundle args = new Bundle();
args.putString(QUERY, query);
fragment.setArguments(args);
return fragment;
}
public RecyclerViewFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mCatId = getArguments().getInt(CAT_ID, -1);
mQuery = getArguments().getString(QUERY, "");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recycler_view, container, false);
// Pull to refresh layout
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
mLoadingView = (TextView) rootView.findViewById(R.id.text_view_loading);
mLayoutManager = new LinearLayoutManager(getActivity());
// Pull to refresh listener
mSwipeRefreshLayout.setOnRefreshListener(this);
// RecyclerView adaptor for Post object
mAdaptor = new MyRecyclerViewAdaptor(postList, new MyRecyclerViewAdaptor.OnItemClickListener() {
#Override
public void onItemClick(Post post) {
mListener.onPostSelected(post, isSearch);
}
});
mRecyclerView.setHasFixedSize(true); // Every row in the list has the same size
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdaptor);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
// Automatically load new posts if end of the list is reached
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//super.onScrolled(recyclerView, dx, dy);
mVisibleItemCount = mLayoutManager.getChildCount();
mPastVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
int totalItemCount = mLayoutManager.getItemCount();
if (mPostNum > mPreviousPostNum && !postList.isEmpty() && mVisibleItemCount != 0 &&
totalItemCount > mVisibleItemCount && !isLoading &&
(mVisibleItemCount + mPastVisibleItems) >= totalItemCount) {
loadNextPage();
// Update post number
mPreviousPostNum = mPostNum;
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
loadFirstPage();
}
/**
* Load the first page of a category
*/
public void loadFirstPage(){
mPage = 1; // Reset page number
if (postList.isEmpty()) {
showLoadingView();
// Reset post number to 0
mPreviousPostNum = 0;
loadPosts(mPage, false);
} else {
hideLoadingView();
}
}
/**
* Load the next page of a category
*/
public void loadNextPage(){
mPage ++;
loadPosts(mPage, true);
}
/**
* Load posts from a specific page number
*
* #param page Page number
* #param showLoadingMsg Flag to determine whether to show Toast loading msg to inform the user
*/
private void loadPosts(int page, final boolean showLoadingMsg) {
Log.d(TAG, "----------------- Loading category id " + mCatId +
", page " + String.valueOf(page));
isLoading = true;
if (showLoadingMsg) {
Toast.makeText(getActivity(), getString(R.string.loading_articles),
Toast.LENGTH_LONG).show();
}
// Construct the proper API Url
String url;
if (!mQuery.isEmpty()) { // Not empty mQuery means this list is for search result.
isSearch = true;
url = Config.BASE_URL + "?json=get_search_results&search=" + mQuery +
"&page=" + String.valueOf(page);
} else { // Empty mQuery means normal list of posts
isSearch = false;
if (mCatId == 0) { // The "All" tab
url = Config.BASE_URL + "?json=get_posts&page=" + String.valueOf(page);
} else { // Everything else
isSearch = false;
url = Config.BASE_URL + "?json=get_category_posts&category_id=" + String.valueOf(mCatId)
+ "&page=" + String.valueOf(page);
}
}
Log.d(TAG, url);
// Request post JSON
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
mSwipeRefreshLayout.setRefreshing(false); // Stop when done
// Parse JSON data
postList.addAll(JSONParser.parsePosts(jsonObject));
// A temporary workaround to avoid downloading duplicate posts in some
// rare circumstances by converting ArrayList to a LinkedHashSet without
// losing its order
Set<Post> set = new LinkedHashSet<>(postList);
postList.clear();
postList.addAll(new ArrayList<>(set));
mPostNum = postList.size(); // The newest post number
Log.d(TAG, "Number of posts: " + mPostNum);
mAdaptor.notifyDataSetChanged(); // Display the list
// Set ListView position
if (RecyclerViewFragment.this.mPage != 1) {
// Move the article list up by one row
// We don't actually need to add 1 here since position starts at 0
mLayoutManager.scrollToPosition(mPastVisibleItems + mVisibleItemCount);
}
// Loading finished. Set flag to false
isLoading = false;
hideLoadingView();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
isLoading = false;
hideLoadingView();
mSwipeRefreshLayout.setRefreshing(false);
volleyError.printStackTrace();
Log.d(TAG, "----- Error: " + volleyError.getMessage());
// Show a Snackbar with a retry button
Snackbar.make(mRecyclerView, R.string.error_load_posts,
Snackbar.LENGTH_LONG).setAction(R.string.action_retry,
new View.OnClickListener() {
#Override
public void onClick(View v) {
//loadFirstPage();
loadPosts(mPage, true);
}
}).show();
}
});
// Set timeout to 10 seconds instead of the default value 5 since my
// crappy server is quite slow
request.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Add request to request queue
AppController.getInstance().addToRequestQueue(request, TAG);
}
#Override
public void onRefresh() {
// Clear the list
postList.clear();
mAdaptor.notifyDataSetChanged();
loadFirstPage();
}
/**
* Show the loading view and hide the list
*/
private void showLoadingView() {
mRecyclerView.setVisibility(View.INVISIBLE);
mLoadingView.setVisibility(View.VISIBLE);
}
/**
* Hide the loading view and show the list
*/
private void hideLoadingView() {
mLoadingView.setVisibility(View.INVISIBLE);
mRecyclerView.setVisibility(View.VISIBLE);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (PostListListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() +
"must implement PostListListener");
}
}
// Interface used to communicate with MainActivity
public interface PostListListener {
void onPostSelected(Post post, boolean isSearch);
}
}
This is fragment_recyclerview.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.declangao.wordpressreader.app.RecyclerViewFragment">
<!-- Article list -->
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/swipe_refresh_layout" >
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:id="#+id/recycler_view" />
</android.support.v4.widget.SwipeRefreshLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/text_view_loading"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center"
android:text="#string/loading_articles"/>
I want to make an App, which has a NavigationView and some fragments. I have no problem to display the different fragments and to navigate inside the application. But I did not manage to implement buttons inside my fragments.
Nothing happens when I click on the button. However I don't have any error.I have searched on Internet and I really don't understand why it doesn't work.I used the same method as in "classic" activity. I guess there is a problem withb.setOnClickListener(this). I pasted my code. I hope one of you will see my error. Thanks a lot for reading.
Accueil.java (mainActivity):
public class Accueil extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
HomeFragment.OnFragmentInteractionListener,Settings_accountFragment.OnFragmentInteractionListener {
NavigationView navigationView;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private static UserLocalStore userLocalStore;
private static User user;
public Intent login;
//private TextView eventName,eventPlace,eventSchedule;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil);
userLocalStore=new UserLocalStore(this);
login=new Intent(this,LoginActivity.class);
navigationView = (NavigationView) findViewById(R.id.nav_view);
fragmentManager = getFragmentManager();
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, myToolbar, 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);
loadSelection(0);
}
private void loadSelection(int i){
switch (i){
case 0:
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentholder,homeFragment);
fragmentTransaction.commit();
break;
case 1:
Settings_accountFragment settings_account = new Settings_accountFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentholder,settings_account);
fragmentTransaction.commit();
break;
default:
break;
}
}
#Override
protected void onStop() {
//userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
userLocalStore.deleteCurrentUser();
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
if(userLocalStore.getUserLoggedIn()) {
user=userLocalStore.getLoggedInUser(userLocalStore.getCurrentUser());
int i=0;
//How to change elements in the header programatically
View headerView = navigationView.getHeaderView(0);
TextView emailText = (TextView) headerView.findViewById(R.id.mail_header);
emailText.setText(user.getMail());
}
}
#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) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_acc) {
// Handle the camera action
loadSelection(0);
} else if (id == R.id.nav_param) {
} else if (id == R.id.nav_param_compte) {
loadSelection(1);
} else if(id==R.id.logOut){
userLocalStore.setUserLoggedIn(false);
userLocalStore.deleteCurrentUser();
startActivity(login);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.menu_calendar, 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();
return super.onOptionsItemSelected(item);
}
public static User getUser() {
return user;
}
public static UserLocalStore getUserLocalStore() {
return userLocalStore;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
/*public void setEventNameText(String name) {
this.eventName.setText(name);
}
public void setEventPlaceText(String place) {
this.eventName.setText(place);
}
public void setEventScheduleText(String schedule) {
this.eventName.setText(schedule);
}*/
/*#Override
public Dialog onCreateDialog (int id) {
Dialog box = null;
switch(id) {
// Quand on appelle avec l'identifiant de la boîte normale
case ID_NORMAL_DIALOG:
box = new Dialog(this);
box.setTitle("Je viens tout juste de naître.");
break;
// Quand on appelle avec l'identifiant de la boîte qui s'énerve
case ID_ENERVEE_DIALOG:
box = new Dialog(this);
box.setTitle("ET MOI ALORS ???");
}
return box;
}
#Override
public void onPrepareDialog (int id, Dialog box) {
if(id == ID_NORMAL_DIALOG && compteur > 1)
box.setTitle("On est au " + compteur + "ème lancement !");
//On ne s'intéresse pas au cas où l'identifiant vaut 1, puisque cette boîte affiche le même texte à chaque lancement
}*/
}
Settings_accountFragment.java :
public class Settings_accountFragment extends Fragment implements View.OnClickListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Button b;
View v;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Settings_accountFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Settings_accountFragment.
*/
// TODO: Rename and change types and number of parameters
public static Settings_accountFragment newInstance(String param1, String param2) {
Settings_accountFragment fragment = new Settings_accountFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v=inflater.inflate(R.layout.fragment_settings_account, container, false);
b=(Button)v.findViewById(R.id.button);
b.setOnClickListener(this);
return inflater.inflate(R.layout.fragment_settings_account, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button:
Log.d("coucou","true");
break;
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
fragment_settings_account.xml:
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/parametre_compte"
android:background="#color/grey"
android:gravity="center"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</FrameLayout>
You are not showing the correct view that has the button you set the click listener on because you are inflating the view again and returning it in onCreateView().
Replace
return inflater.inflate(R.layout.fragment_settings_account, container, false);
With
return v;
So that you return the view you already inflated.
In Settings_accountFragment:onCreateView you are inflating the view twice. Remove the second inflate code and just return v;
v=inflater.inflate(R.layout.fragment_settings_account, container, false);
b=(Button)v.findViewById(R.id.button);
b.setOnClickListener(this);
return v;
Also, a side note - it's not common to use '_' in Java class names. SettingsAccountFragment is a better than Settings_accountFragment
I would like to expose my problem and I want to know how I could solve it.
In my application I'm using an activity, making a simple login, launching a asyncTask. At the end of this task, the user is redirected to another activity, which is the home activity of application. The latter has the task of managing a navigation drawer and its fragments. The contents of each fragment must be populated with data retrieved from a server and the navigation drawer set the default fragment F1, which is displayed after the user has logged on.
Now the problem is:
How can I recover the data necessary to populate the listView contained in fragment1?
I know how to implement an adapter for the listView, but I don't understand how to communicate the home activity with the fragment F1. My intention would be to retrieve a circular dialog (content in F1) and run it as long as the data required for the adapter have not been recovered.
Here some code:
public class LoginActivity extends ActionBarActivity {
private Button loginButton;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Login().execute();
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class Login extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("Login");
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (progessDialog.isShowing()) {
progressDialog.dismiss();
}
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Bundle bundle = new Bundle();
intent.putExtras(bundle);
startActivity(intent);
}
#Override
protected Void doInBackground(String... params) {
// code to retrieve data.
}
}
}
public class HomeActivity extends ActionBarActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar toolbar;
private FragmentDrawer fragmentDrawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(false);
fragmentDrawer = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
fragmentDrawer.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
fragmentDrawer.setDrawerListener(this);
// Here the problem!!!
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displayView(int position) {
switch (position) {
case 0:
Fragment fragmentOne = new FragmentOne();
move(matchFragment);
break;
case 1:
Fragment fragmentTwo = new FragmentTwo();
move(teamFragment);
break;
case 2:
Fragment fragmentThree = new FragmentThree();
move(myTeamFragment);
break;
case 3:
//other fragment....
default:
break;
}
}
public void move (Fragment fragment) {
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment, fragment.getClass().getSimpleName());
fragmentTransaction.commit();
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
}
public class FragmentOne extends Fragment {
private ListView listView;
private ArrayList<Info> infos;
private InfoAdapter infoAdapter;
public FragmentOne() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_match, container, false);
listView = (ListView) rootView.findViewById(R.id.match_list_view);
return rootView;
}
}
Now, where do I implement the AsyncTask to retrieve data for adapter? In fragment or the Activity?
If it were the Activity, how can I recover the elements of view of fragment?
Thanks in advance and sorry for bad english.
for your first quesiton:
I don't understand how to communicate the home activity with the
fragment F1
You can pass information from HomeActivity to the Fragment through parameters passed to the Fragment's constructors. So instead of Fragment fragmentOne = new FragmentOne();, you can call Fragment fragmentOne = new FragmentOne(A a); where a is data you want to pass to the fragment. Of course, you need to add in the constructor with parameters to the Fragment class.
For the 2nd point:
Now, where do I implement the AsyncTask to retrieve data for adapter?
In fragment or the Activity? If it were the Activity, how can I
recover the elements of view of fragment?
You can put AsynchTask call inside onCreate() to load data for the listView...etc. Another option which I prefer is to use Loaders. Please see this documentation on Loaders here http://developer.android.com/guide/components/loaders.html. It also has an example.
For explanation and sample, you can follow these 4-part tutorials:
http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html.
This appears to have been asked a lot on stack overflow, but with answers which appear to no longer be implementable with changes to the SDK (I may be wrong!).
I have been trying to allow a fragment inside my MainActivity to use the hardware button to go back to the previous page inside a webview in the fragment.
I have tried using return super.onKeyDown(keyCode, event);
as part of a function but onKeyDown does not come up as valid in my project.
This is my BlogFragment containing the webview:
public class BlogFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
WebView wv;
private OnFragmentInteractionListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment blog.
*/
// TODO: Rename and change types and number of parameters
public static BlogFragment newInstance(String param1, String param2) {
BlogFragment fragment = new BlogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static boolean canGoBack(){
return wv.canGoBack();
}
public static void goBack(){
wv.goBack();
}
public BlogFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_blog, null);
wv = (WebView) view.findViewById(R.id.webview);
WebSettings settings = wv.getSettings();
wv.setWebChromeClient(new WebChromeClient() {
});
final String mimeType = "text/html";
final String encoding = "UTF-8";
String html = getHTML();
settings.setJavaScriptEnabled(true);
wv.loadDataWithBaseURL("http://www.bbc.co.uk", html, mimeType, encoding, "");
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public String getHTML() {
String html = "<iframe width=\"100%\" height=\"100%\" src=\"http://blog.mrgyro.co.uk\" frameborder=\"0\" allowfullscreen></iframe>";
return html;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
Activity:
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks, BlogFragment.OnFragmentInteractionListener, HomeFragment.OnFragmentInteractionListener {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onBackPressed() {
if(BlogFragment.canGoBack()){
BlogFragment.goBack();
}else{
super.onBackPressed();
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
switch (position) {
case 0:
HomeFragment homeFragment = new HomeFragment();
transaction.replace(R.id.container, homeFragment);
break;
case 1:
BlogFragment blogFragment = new BlogFragment();
transaction.replace(R.id.container, blogFragment);
break;
}
transaction.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;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given 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 = null;
rootView = inflater.inflate(R.layout.fragment_home, container, false);
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
rootView = inflater.inflate(R.layout.fragment_home, container, false);
break;
case 2:
rootView = inflater.inflate(R.layout.fragment_blog, container, false);
break;
case 3:
// rootView = inflater.inflate(R.layout.fragment_test, container, false);
break;
case 4:
//rootView = inflater.inflate(R.layout.fragment_info, container, false);
break;
default:
Log.e("TAG", "Unrecognized section: " + getArguments().getInt(ARG_SECTION_NUMBER));
}
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Thanks in advance.
EDIT: I have updated the blog fragment with my most recent attempt, however when trying to static wv.canGoBack() and wv.goBack() both return the error "Non-Static field 'wv' cannot be referenced from a static context
Try overriding onBackPressed() in your Activity and make it poke the WebView.
BTW - you could post the piece of Activity containing the onKeyDown method as well.
EDIT: Instead of making your methods static and accessing them the way you do now (BlogFragment.canGoBack()), first instantiate the fragment:
BlogFragment blogFragment = new BlogFragment();
blogFragment.canGoBack();
and then just remove the static from your methods. :)
OPs implementation (with thanks to Klotor)
At the head of MainActivity implement:
BlogFragment blogFragment = new BlogFragment();
Then implement:
public void onBackPressed() {
blogFragment.canGoBack();
if(blogFragment.canGoBack()){
blogFragment.goBack();
}else{
super.onBackPressed();
}
}
The fragment is instantiated outside of the onBackPressed in order to prevent crashing when using a method to navigate between fragments.
In this case you need to instantiate a newinstance of the fragment, rather than a whole new fragment.
** In your Fragment Class Inside OnCreateView put below code**
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.your_layout, container, false);
mWebView = (WebView) view.findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.loadUrl(expertsUrl);
return view;
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
**In MainActivity class put below code **
#Override
public void onBackPressed() {
if (WebViewFragment.mWebView!=null) {
if (WebViewFragment.mWebView.canGoBack()) {
WebViewFragment.mWebView.goBack();
}
else {
super.onBackPressed();
}
}
}
Replace WebViewFragment -> with your Fragment
mWebView -> with your webview
Hope this will help you!!!!