I am using two Activities. One is MainActivity and the second one is for NFC. MainActivity has nav_graph.xml.
After reading the NFC, I'd like to start MainActivity and move to a certain fragment of MainActivity.
How can I implement this?
You can try this:
(in MainActivity.java)
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 0:
Frag1 frag1 = new Frag1();//this is one activity
return frag1;
case 1:
Frag2 frag2 = new Frag2();
return frag2;
default:
return null;
}
}
#Override
public int getCount() {
return 2; //'the number 2 is 'cause you've got a two activities
}
}
and if you want open another activity with de floating action button, you can try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mViewPager.getCurrentItem()==0){
Fragment1();
Toast.makeText(MainActivity.this, "Example 1", Toast.LENGTH_SHORT).show();
}else if(mViewPager.getCurrentItem()==1){
Fragmen2();
Toast.makeText(MainActivity.this, "Example 2", Toast.LENGTH_SHORT).show();
}
}
});
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
}
public void Fragment1(){//Call to the activity Example1
Intent fragment0 = new Intent(getApplicationContext(), example1.class);
startActivity(fragment0);
onResume();
}
public void Fragmen2(){ //Call to the activity Example2
Intent fragment1 = new Intent(getApplicationContext(), example2.class);
startActivity(fragment1);
onResume();
}
Related
I have used Tab Control and RecyclerView together in Android. The way it functions is I have SearchBar in the toolbar. When the user enters the search query in the search bar. Upon hitting the search button, tab's Fragments are supposed to be loaded with data. Issues are as follows.
1) Tabs icon disappear
2) When debugging through the code found (Since I am using ViewPager with Tab Layout to implement Tabs in android) that getItem method of PagerAdapter class is called twice every time getItem is triggered.
I am stuck and don't know what to do. Not much help online as well.
1) Tab initialization Code:-
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.craigslist_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.kijiji_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.letgo_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.varagesale_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.facebook_new1));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
drawerLayout = findViewById(R.id.drawer_layout);
}
#Override
public boolean onQueryTextSubmit(String query) {
//loadRecyclerViewData(query);
Bundle bundle = new Bundle();
bundle.putString("searchText", query);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), bundle);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return true;
}
2) PagerAdapter:-
public class PageAdapter extends FragmentStatePagerAdapter {
int mNoofTabs;
Bundle bundle;
public PageAdapter(FragmentManager fragmentManager, int NumberOfTabs, Bundle bundle)
{
super(fragmentManager);
this.mNoofTabs = NumberOfTabs;
this.bundle = bundle;
}
#Override
public Fragment getItem(int i) {
switch(i)
{
case 0 :
CraigslistFragment tab1 = new CraigslistFragment();
tab1.setArguments(bundle);
return tab1;
case 1:
KijijiFragment tab2 = new KijijiFragment();
tab2.setArguments(bundle);
return tab2;
case 2:
letgoFragment tab3 = new letgoFragment();
tab3.setArguments(bundle);
return tab3;
case 3:
VaragesaleFragment tab4 = new VaragesaleFragment();
tab4.setArguments(bundle);
return tab4;
case 4:
FacebookFragment tab5 = new FacebookFragment();
tab5.setArguments(bundle);
return tab5;
default:
return null;
}
}
#Override
public int getCount() {
return mNoofTabs;
}
}
First of all I am new to Android development, and I would appreciate your help.
I have a tabbed activity in android studio and I have a FloatingActionButton to add an Item in each fragment of the tabbed activity. This button then calls a new Activty and I would like to pass to the new activity the tab Number, so that I can store it in a database.
How can I get the tab Number that the new activity was generated from?
Below is the code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_portal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startNewPostActivity = new Intent(getApplicationContext(), NewPostActivity.class);
startNewPostActivity.putExtra("Fragment_Position", position_fragment);
startActivity(startNewPostActivity);
}
});
}
To get the position I was doing the following :
Setting position_fragment = position;
however this returns wrong tab Number.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
position_fragment = position; // not good
return PlaceholderFragment.newInstance(position);
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
}
}
Try this:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startNewPostActivity = new Intent(getApplicationContext(), NewPostActivity.class);
startNewPostActivity.putExtra("Fragment_Position", mViewPager.getCurrentItem());
startActivity(startNewPostActivity);
}
});
You can identify your tab id from these switch case and call necessary function inside
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());//setting current selected item over viewpager
switch (tab.getPosition()) {
case 0:
//Log.e("TAG","TAB1");
break;
case 1:
//Log.e("TAG","TAB2");
break;
case 2:
//Log.e("TAG","TAB3");
break;
case 3:
//Log.e("TAG","TAB4");
break;
case 4:
//Log.e("TAG","TAB5");
break;
case 5:
//Log.e("TAG","TAB6");
break;
case 6:
//Log.e("TAG","TAB7");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
There are two ways to get number of the Current Tab in Tabbed Activity
1. use ViewPager.getCurrentItem()
Returns the number of pages that will be retained to either side of the current page in the view hierarchy in an idle state. Defaults to 1.
SAMPLE CODE
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent startNewPostActivity = new Intent(getApplicationContext(), NewPostActivity.class);
startNewPostActivity.putExtra("Fragment_Position", mViewPager.getCurrentItem());
startActivity(startNewPostActivity);
}
2. Use TabLayout.addOnTabSelectedListener()
Add a TabLayout.OnTabSelectedListener that will be invoked when tab selection changes.
SAMPLE CODE
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Working With Android Framgent,I having Three fragments layout i want to hide fragment on the basis of flag.When First fragment is visible want disable second fragment
Am successfully able to hide tab headings of tab layout but not able to remove Page.How to achive it.?
I have searched alot but didn't find as i accepted.
public class Sample extends AppCompatActivity implements Commands.FragmentDataListener_Commands_epg{
Bundle dataBundle;
TabLayout tabLayout;
String flag;
private Sample.SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
flag = intent.getStringExtra("flag");
mSectionsPagerAdapter = new Sample.SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
if(flag.equals("1")) {
tabLayout.removeTabAt(0);
}
else if(flag.equals("2"))
{
tabLayout.removeTabAt(1);
}
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
#Override
public void onStart() {
super.onStart();
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
//first page
case 1:
//second page
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First";
case 1:
return "second";
}
return null;
}
}}
Thank you in advance.
Since you get the flag in intent, you don't need tabLayout. Just init and the fragment to your view.
Some code like below:
Fragment fragmentInput = new FragmentAddVehicle();
FragmentManager getSupportFragmentManager.beginTransaction().add(R.id.ll_root_container, fragmentInput).commit();
I want to call my tablayout activity , when user clicked on Item Menu from Action View Item ,
But I am getting error :
06-15 14:17:01.604: E/AndroidRuntime(1365): java.lang.NoClassDefFoundError: Failed resolution of: Linfo/muscle/reboot/activity/Wrk_plan_gain;
Here is my Main activity from where I am calling Tab layout Activity .
MainActivity:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
public MainActivity() {
// Required empty public constructor
}
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
SharedPreferences pref;
String diet_saved;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = this.getPreferences(1);
diet_saved=pref.getString("diettype", "main");
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.workout_menu) {
startActivity(new Intent(MainActivity.this, Wrk_plan_gain.class));
finish();
return true;
}
/*if(id == R.id.action_search){
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
}
*/
return super.onOptionsItemSelected(item);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new KnowYourBodyFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new YourResultFragment();
title = getString(R.string.title_messages);
break;
case 3:
fragment = new YourMacroResultFragment();
title = getString(R.string.title_macro);
break;
case 4:
fragment = new DietPlanFragment();
title = getString(R.string.title_Diet);
break;
case 5:
title = getString(R.string.title_Exit);
finish();
break;
default:
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
and I am trying call this Activity
public class Wrk_plan_gain extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
public Wrk_plan_gain() {
// Required empty public constructor
}
//This is our tablayout
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wrk_plan_layout_gain);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
Also it will every much help full I f I can call this activity from Nav drawer Item ..
I am not able to get it work , in both cases .
I have a Navigation Drawer (so I use Fragments):
MainActivity (FragmentActivity)
Fragment A (Fragment with pictures links for Fragment B, C & D)
Fragment B (Fragment)
Fragment C (Fragment)
Fragment D (Fragment)
My navigation drawer works correctely, but I want to my Fragment A to do links like the menu. Right now, in Fragment A, I call the other Fragments like this:
ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Fragment fragment = new ContactezNous();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.accueil, fragment);
fragmentTransaction.commit();
}
});
But I don't want to use this way, because I have problems finding tags and ids of other Fragments.
I want to know how to change Fragments frome Fragment A by clicking on the link like if I was clicking on the Navigation Drawer links of the Main Activity.
Main Activity:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
//Initialisation de l activite avec les donnees necessaires
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerFragment = (FragmentDrawer) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// Affichage de la navigation
displayView(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Ajout des items
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);
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new Accueil();
title = getString(R.string.title_accueil);
break;
case 1:
fragment = new NosOffres();
title = getString(R.string.title_nosoffres);
break;
case 2:
fragment = new DemandeGratuite();
title = getString(R.string.title_demandegratuite);
break;
case 3:
fragment = new ContactezNous();
title = getString(R.string.title_contact);
break;
case 4:
fragment = new Actualites();
title = getString(R.string.title_actu);
break;
case 5:
fragment = new MentionsLegales();
title = getString(R.string.title_mentions);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
//fragmentTransaction.addToBackStack("name");
fragmentTransaction.commit();
// libelle du toolbar
TextView titlet;
titlet = (TextView) findViewById(R.id.main_toolbar_title);
titlet.setText(title);
titlet.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/GothamBook.ttf"));
}
}
}
You should use the following common Android fragment pattern:
public class Accueil extends Fragment {
// Your code here...
public interface OnFragmentInteractionListener {
void onInteraction(int id);
}
private OnFragmentInteractionListener mListener;
#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;
}
// ...more code...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...initialize your View...
ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This is how you use the listener
mListener.onInteraction(3);
}
});
// ...more initialization...
}
}
MainActivity.java
public class MainActivity AppCompatActivity
implements FragmentDrawer.FragmentDrawerListener, OnFragmentInteractionListener {
// Your code here...
// Implement OnFragmentInteractionListener
#Override
public void onInteraction(int id) {
// 'id' would be '3' for your 'ContactezNous' fragment
displayView(id);
}
}