I need to call the activity interface method onDrawerItemSelected(view,position) in fragment page.is it possible.anyone can help me with this.So that I can do a custom drawer in fragment page.
MainActivity.java:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
#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 UserProfileFragment();
title = getString(R.string.title_discovery);
break;
case 1:
fragment = new SettingsActivity();
title = getString(R.string.title_messages);
break;
case 2:
fragment = new InboxRequestActivity();
title = getString(R.string.title_discovery);
break;
case 3:
break;
default:
break;
}
}
CustomFragment.java:
public class CustomFragment extends Fragment implements FragmentDrawer.FragmentDrawerListener
menu_btn_click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
on clicking the menu_btn_click, I need to call the activity interface method onDrawerItemSelected(view,position) in fragment page.
You need to override the onDrawerItemSelected(View view, int position) method in your fragment and call it on your activity:
#Override
public void onDrawerItemSelected(View view, int position) {
listener.onDrawerItemSelected(view, position);
}
therefor you will need to pass the activity as FragmentDrawer.FragmentDrawerListener to the fragment (e.g. by an appropiate setter).
setListener(FragmentDrawer.FragmentDrawerListener listener){
this.listener = listener;
}
Related
I have an Activity. When I click on the button, I want to run the method in Fragment. But it does not work. I tried many ways, but I could not get it working.
My Activity;
public class MyActivity extends Activity {
Button button;
TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myactivity_main);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("First"));
tabLayout.addTab(tabLayout.newTab().setText("Second"));
viewPager= (CustomViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
});
button = (Button)findViewById(R.id.button);
button .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyFragment firstfragment = (MyFragment ) getFragmentManager().findFragmentByTag(“tab1”);
firstfragment.MyMethod();
}
});
}
}
MyFragmentAdapter
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.webviewapp.Fragment.PromotionFragment;
import com.webviewapp.Fragment.WebFragment;
public class MyFragmentAdapter extends FragmentPagerAdapter {
int tabCount;
public MyFragmentAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FirstFragment tab1 = new FirstFragment ();
return tab1;
case 1:
SecondFragment tab2 = new SecondFragment ();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
FirstFragment
public class FirstFragmentextends Fragment {
Button fragmentbutton;
public FirstFragment() {
// Required empty public constructor
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_web, container, false);
fragmentbutton = (Button) view.findByViewId(R.id.fragmentbutton );
}
public void MyMethod(){
fragmentbutton.setVisibility(View.GONE);
}
}
I'm sorry to cause confusion. What I'm trying to do is to run MyMethod when I press the button in Activity. MyMethod is a special method in the fragment. I apologize again for not being able to add the codes at first.
If you want to call a method from FirstFragment
FirstFragment firstFragment = (FirstFragment) getSupportFragmentManager().getFragments().get(0);
firstFragment.MyMethod();
If you want to call a method from SecondFragment
SecondFragment secondFragment = (SecondFragment) getSupportFragmentManager().getFragments().get(1);
secondFragment.MyMethod();
The index 0 or 1 based on position in getItem method of your adapter.
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
FirstFragment tab1 = new FirstFragment();
return tab1;
case 1:
SecondFragment tab2 = new SecondFragment();
return tab2;
default:
return null;
}
}
Then give it a try.
You use FragmentManager to get a handle on the fragment.
You are making a new instance of a Fragment in your code:
final FirstFragment firstfragment= new FirstFragment ();
Where that new object is not bound to any activity.
FragmentManager
Too late for answering the question but this is a easy way to get fragment instance and call methods in a fragment; you have to get instance of your fragment then call your public method:
In your fragment :
private static yourFragment instance;
then in onCreateView of your fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
instance= this;
View v = inflater.inflate(R.layout.fragment_tools, container, false);
binding = FragmentToolsBinding.inflate(inflater, container, false);
return v;
}
and also in your fragment you have to have a static method that returns the instance:
public static yourFragment GetInstance()
{
return instance;
}
then you have a public method in in your fragment that you want to call it like this:
public void theMethod()
{
Toast.makeText(getActivity(), "Test", Toast.LENGTH_SHORT).show();
}
then you can get fragment instance and call your non static public method like this:
yourFragment frag = yourFragment.GetInstance();
frag.theMethod();
I need some help with setting up the position of the Fragments in order for it to work with the the onPageListener so I can set the visibility of certain views. As I am new, I am rather unsure on how to do this. Thank you for your time and effort.
MainActivity.java
public class MainActivity extends FragmentActivity {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
drawerGrid = (GridView) findViewById(R.id.content);
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(1);
viewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//need some help here//
if(position == 1) {
drawerGrid.setVisibility(View.VISIBLE);
} else {
drawerGrid.setVisibility(View.GONE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Fragments.java
public class Fragments extends FragmentPagerAdapter {
public Fragments(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //need some help here//
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
try this:
ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
drawerGrid.setVisibility(View.GONE);
break;
case 1:
drawerGrid.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
use it like:
ViewPager.addOnPageChangeListener(pageChangeListener);
// do this in a runnable to make sure the viewPager's views are already instantiated before triggering the onPageSelected call
viewpager.post(new Runnable()
{
#Override
public void run()
{
pageChangeListener .onPageSelected(viewPager.getCurrentItem());
}
});
I have a floating button in one of my fragments.On click of which an
activity pops up.Now the problem is when I go back from the activity
to the fragment the fragment does not auto refresh.Also I want it to
refresh on back pressed.
Within the fragment I have a refresh button in the action bar on
pressed of which I call a refreshFragment() method.Is there a way in
android that I can call a method from a fragment from within an
activity.
This is my refreshFragment() method code.
public void refreshFragment()
{
Fragment fragment = new BillingFragment();
android.support.v4.app.FragmentManager fragmentMg = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTrans = fragmentMg.beginTransaction();
fragmentTrans.replace(R.id.container_body, fragment, "TABBILLING");
fragmentTrans.addToBackStack(null);
fragmentTrans.commit();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Billing");
//adapter.notifyDataSetChanged();
}
And I call it inside my on create view method as follows :-
((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener()
{
#Override
public void onRefresh() {
refreshFragment();
}
});
I even tried calling displayView() method of my main activity from
another activity by creating an object of MainActivity as follows:-
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
MainActivity main = new MainActivity();
main.displayView(1);
count = 0;
return true;
But it gave me a null pointer exception.This is my displayView() method.
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
public 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 BillingFragment();
title =getString(R.string.title_billing);
break;
case 2:
fragment = new StockViewFragment();
title =getString(R.string.title_stockview);
break;
case 3:
fragment = new BhishiManagementFragment();
title= getString(R.string.title_bhishiview);
break;
case 4:
fragment = new ReportingFragment();
title=getString(R.string.title_reporting);
break;
case 5:
fragment = new VendorManagementFragment();
title=getString(R.string.title_vendormanagement);
break;
case 6:
fragment = new CustomerMgmt();
title = getString(R.string.title_custmgmt);
break;
default:
break;
}
Any help is appreciated.Thank you :)
I assume you are trying to refresh fragment when coming back from an activity (that activity does not hosting the fragment which needs to be refreshed), if my assumption is correct please try the below approach, incase not please clarify the question with more info.
Try : Have a boolean variable in fragment and update its value true or false based on fragment visible state using its lifecycle methods.
public class SampleFragment extends Fragment {
private boolean shouldRefreshOnResume = false;
public static SampleFragment newInstance() {
SampleFragment fragment = new SampleFragment();
return fragment;
}
public SampleFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank,
container, false);
}
#Override
public void onResume() {
super.onResume();
// Check should we need to refresh the fragment
if(shouldRefreshOnResume){
// refresh fragment
}
}
#Override
public void onStop() {
super.onStop();
shouldRefreshOnResume = true;
}
}
I am trying to implement swipe views with android. I am using a ViewPager with two tabs containing fragments. In my onCreate() method, I am trying to read from a sharedPrefferences and according to what i am getting, i want to change text and visibility to some child views of the parent view of the first fragment. Unfortunately i am always getting NullPointerException when i am trying to access fragments views.
My sample code from the one of the two fragments is given below. Could you please help me ? Is there a better way to do so?
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
context = getApplicationContext();
myTabPagerAdapter = new TabPagerAdapter(getSupportFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.pager);
myViewPager.setAdapter(myTabPagerAdapter);
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(MainActivity.this, "Selected page position: " + position, Toast.LENGTH_SHORT).show();
getActionBar().setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
myViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
actionBar.addTab(actionBar.newTab().setText("Spot Position").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Track Vehicle").setTabListener(tabListener));
//Get saved latitude and longitude from sharedPreferences
sharedPref = context.getSharedPreferences("net.ddns.drimou.bachelorthesis", Context.MODE_PRIVATE);
editor = sharedPref.edit();
}
#Override
protected void onStart() {
super.onStart();
getSharedPreferencesOnStart();
}
public void getSharedPreferencesOnStart() {
String s = myTabPagerAdapter.makeFragmentName(myViewPager.getId(),myViewPager.getCurrentItem());
SpotPosition sp = (SpotPosition) myTabPagerAdapter.getItem(0);
sp.setSettings();//In this call i am getting null pointer
...}
Fragment A
public class SpotPosition extends Fragment {
TextView locationTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View spotPosition = inflater.inflate(R.layout.spot_position, container, false);
return spotPosition;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void setSettings(){
locationTextView = (TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
TabPagerAdapter
public class TabPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
private View mCurrentView;
private SpotPosition sp = null;
private static int NUM_ITEMS = 2;
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
//Fragment for SpotPosition myViewPager
return new SpotPosition();
case 1:
//Fragment for TrackVehicle myViewPager
return new TrackVehicle();
}
return null;
}
#Override
public int getCount() {
return NUM_ITEMS; //Number of Tabs
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
sp = (SpotPosition)object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public CharSequence getPageTitle(int position) {
switch(position) {
case 0:
return "Spot Position";
case 1:
return "Track Vehicle";
default:
return null;
}
}
public String makeFragmentName(int viewId, int index) {
return "android:switcher:" + viewId + ":" + index;
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
public View getCurrentView(){
return this.mCurrentView;
}
public SpotPosition getCurrentSpotPosition(){
return this.sp;
}
Feel free to ask if something is not understood. Thank you
As far as I understand you call setSettings from you activity, to change views in you fragment. You did not provide stacktrace and i assume you problem - attempt to change view after onPause was called in offcreen fragment. There are several ways to deal with it.
First of all dont call to views dirrectly.
On activity
public void getSharedPreferencesOnStart() {
String s = myTabPagerAdapter.makeFragmentName(myViewPager.getId(),myViewPager.getCurrentItem());
SpotPosition sp = (SpotPosition) myTabPagerAdapter.getItem(0);
// sp.setSettings();//In this call i am getting null pointer
SharedPreferences prefs = getSharedPreferences("message",MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putBoolean("say_hello",true")
editor.commit();
...}
in fragments
#Override
public void onResume(){
super.onResume();
SharedPreferences prefs =
getActivity().getSharedPreferences("message", Context.MODE_PRIVATE);
{
//this block is used for offsreen fragment, it will get update, when it go to forescreen
boolean sayHello = prefs.getBoolean("say_hello", false);
if(sayHello){
locationTextView =
(TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}else{
// say something elese
}
}
{
//this listener is for forescreen fragment, as soon as shared preferences will be updated,
// listerner willbe called and you can update your view depending on changed parameters
prefs.registerOnSharedPreferenceChangeListener(
new OnSharedPreferenceChangeListener(){
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key
){
if(key.equals("say_hello")){
boolean sayHello = sharedPreferences.getBoolean("say_hello", false);
if(sayHello){
locationTextView =
(TextView) myView.findViewById(R.id.mainTextView);//NullPointerException here
locationTextView.setVisibility(View.VISIBLE);
locationTextView.setText("Hello");
}else{
// say something elese
}
}
}
}
);
}
}
You also can use Otto bus it is still unsutable for activity to fragment communication, as fragment can be in !isResumed state, but it is usefull fro fragment -activity comunication.
If you need some complex state tracking for each fragment and activity separatly, I'd recomment to use sqlDatabase and CursorLoaders. It will give you good controll over states and instan comunication.
Edit:
Its not that you cannot pass view from fragment to activity with getters.
Problem - you cannot garanty, that you completly aware of state of the fragment and a view. You try to update views on onStart of activity, which is call earlier, then fragmentsonStart, because fragment have to be generated by adapter and go through attachement process. (to find yout if fragment is attached to activity, you have to set listener in activity and call it ononActivityAttached` of fragment. See android studio activity with fragment template). Thus, when you call to change views, fragment and views probably did not exist.
Futhermore you should read about fragment and activity lifecycle and read about context ( espesialy why strong referencing views in unrelated context holder lead to sever memmory leaks and lificle errors
I have an activity with fragment pager and I want to know how to call an asynctask located on that activity from fragment .
AddActivity.java
public class AddActivity extends FragmentActivity {
ViewPager vp;
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
vp = (ViewPager) findViewById(R.id.pager);
PagerAdapter pa = new FragPagerAdapter(getSupportFragmentManager());
vp.setAdapter(pa);
}
//This void to get All field from the differents fragments and put them into jsonObject
protected JSONObject createJsonObjectVR () {
...
}
// Call the Post Method
public class addVR extends AsyncTask<String, String, String> {
...
}
OtherFragment.java
public class OtherFragment extends Fragment {
Button btn;
public OtherFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_other, container, false);
btn = (Button) view.findViewById(R.id.send);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Here I want to call the createVR asynctask in the parent Activity
}
});
return view;
}
}
FragPagerAdapter
public class FragPagerAdapter extends FragmentPagerAdapter {
public FragPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// First Fragment The main
return new FirstFragment();
case 1:
// Milk (Second) fragment activity
return new SecondFragment();
case 2:
// Housing (Third) fragment activity
return new HousingFragment();
case 3:
//Feeding (fourth) fragment activity
return new FeedingFragment();
case 4:
// Other (Fith the last) fragment activity
return new OtherFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 5;
}
}
in your fragment :
((AddActivity) getActivity()).someMethodToCallAsyncTaskInAddActivity();
inf your AddActivity:
public void someMethodToCallAsyncTaskInAddActivity() {
new AsyncTask(someOptions_if_needed).execute();
}
One more option
public static class ASyncronius extends AsyncTask<Void, Void, Void>
if you make it static you can call this async task from anywhere
AddActivity.ASyncronius abs = new AddActivity.ASyncronius ();
abs.execute()
Edit 2014-11-11
if you use fragment in diffrent activitys, then you shuld make shure, that those activitys extends same master class, that contains async method.
class ParentActivity extends Activity {
someMethodToCallAsyncTaskInParentActivity(){
***new async execute***
}
public class async extends AsyncTask<void, void, void>{
***Some stuff***
}
}
Then:
class FirstActivity extends ParentActivity{
}
also
class SecondActivity extends ParentActivity{
}
in your fragment
((ParentActivity)getActivity()).someMethodToCallAsyncTaskInParentActivity();
or if you dont need in that other activity use async task, then just do some thing like this:
try{
((FirstActivity)getActivity()).someMethodToCallAsyncTaskInParentActivity();
} catch( Exception e) {
// this is not needed activity
}