public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupViewPager();
}
private void setupViewPager() {
// TODO Auto-generated method stub
FragmentPagerItemAdapter adapter = new FragmentPagerItemAdapter(
getSupportFragmentManager(), FragmentPagerItems.with(this)
.add("Home", HomeFragment.class)
.add("Message", MessageFragment.class)
.add("My", MyFragment.class).create());
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
SmartTabLayout viewPagerTab = (SmartTabLayout) findViewById(R.id.viewpagertab);
final LayoutInflater inflater = LayoutInflater.from(viewPagerTab.getContext());
final Resources res = viewPagerTab.getContext().getResources();
viewPagerTab.setCustomTabView(new SmartTabLayout.TabProvider() {
#Override
public View createTabView(ViewGroup container, int position,PagerAdapter adapter) {
ImageView icon = (ImageView) inflater.inflate(R.layout.mainactivity_tab, container, false);
switch (position) {
case 0:
icon.setImageDrawable(res.getDrawable(R.drawable.mainactivity_tab_icon_home));
break;
case 1:
icon.setImageDrawable(res.getDrawable(R.drawable.mainactivity_tab_icon_message));
break;
case 2:
icon.setImageDrawable(res.getDrawable(R.drawable.mainactivity_tab_icon_my));
break;
default:
throw new IllegalStateException("Invalid position: "+ position);
}
return icon;
}
});
viewPagerTab.setViewPager(viewPager);
}
Here is the code in that three fragment
public class HomeFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
TextView title = (TextView) rootView.findViewById(R.id.item_title);
title.setText("Home");
return rootView;
}
#Override
public void setMenuVisibility(final boolean visible) {
super.setMenuVisibility(visible);
if (visible) {
Log.d("Action bar", "Home");
ActionBar mActionBar= getActivity().getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mCustomView = mInflater.inflate(R.layout.actionbar_message, null);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
TextView title = (TextView) mCustomView.findViewById(R.id.actionbar_message_title);
title.setText("Home action bar");
}
}
They work on MessageFragment.class and MyFragment but not HomeFragment.
It will crash and ActionBar mActionBar = getActivity().getActionBar(); will return null and crash.
Why it only works on MessageFragment and MyFragment?
HomeFragment is the first fragment to show.
My idea: I will to use different custom action bar on different fragment.
Replace this line
ActionBar mActionBar = getActivity().getActionBar();
by this
ActionBar mActionBar=((ActionBarActivity) getActivity()).getSupportActionBar();
It's because you extended ActionBarActivity
The problem is that your fragment is not attached to an activity when setMenuVisibility is called. Therefore getActivity returns null.
I don't understand why you'd want to mess with this method in the first place. You can just modify the the action bar in your onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
{
TextView title = (TextView) rootView.findViewById(R.id.item_title);
title.setText("Home");
}
ActionBar mActionBar= getActivity().getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(getActivity());
View mCustomView = mInflater.inflate(R.layout.actionbar_message, null);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
TextView title = (TextView) mCustomView.findViewById(R.id.actionbar_message_title);
title.setText("Message action bar");
return rootView;
}
If really do need the use of that method, then you could try a simple null check:
if (visible && getActivity() != null) {
I god the solutions, put my code in setUserVisibleHint
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
}
}
Related
Hi in the below code I have a one fab button if I press the fab button replacing one fragment with another fragment in the meanwhile I am changing the title also.
But fragments are replaced but the title is not changing.
Can anyone help me
OneFragement.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the borderdashboard for this fragment
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Task List");
View rootView = inflater.inflate(R.layout.account_list, container, false);
setHasOptionsMenu(true);
setSearchtollbar();
FloatingActionButton fb = rootView.findViewById(R.id.fab);
fb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDuplicate = "false";
Bundle args = new Bundle();
args.putString("isDuplicate", String.valueOf(isDuplicate));
fragment = new TaskCreateFragement();
sessionId = getActivity().getIntent().getStringExtra("sessionId");
fragment.setArguments(args);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Create New Task");
loadFragment(fragment);
}
});
SecondFragment.java:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the borderdashboard for this fragment
((AppCompatActivity) getContext()).getSupportActionBar().setTitle("Create New Task");
MainActivity.java:
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// getSupportActionBar().setTitle("DASHBOARD");
final ActionBar ab = getSupportActionBar();
ab.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
ab.setCustomView(R.layout.toolbar_spinner);
if (ab != null) {
ab.setDisplayShowTitleEnabled(false);
mTitle = (TextView) findViewById(R.id.toolbar_title);
mTitle.setText("DASHBOARD");
mTitle.setGravity(Gravity.CENTER_HORIZONTAL);
// Typeface typeface = Typeface.createFromAsset(getApplicationContext ().getAssets (), "fonts/astype - Secca Light.otf");
// mTitle.setTypeface (typeface);
}
ab.setHomeAsUpIndicator(R.drawable.menu);
ab.setDisplayHomeAsUpEnabled(true);
You are creating a custom view in your toolbar, so you have to change the text of the TextView inside Toolbar layout.
Create a method in your Activity
public void setActionBarTitle(String title) {
mTitle.seText(title);
}
In SecondFragment change title in onCreate or onResume
((YourActivityClassName)getActivity()).setActionBarTitle("Create New Task");
Create method in your Activity
public void setActionBarTitle(String title) {
mTitle.setText(title); // as you used custom view
}
In SecondFragment change title in onCreate or onResume
((YourActivity)getActivity()).setActionBarTitle("Create New Task");
add this snippet in the onCreate method in the activity where your fragments are hosted and see if your code is working.
#Override
protected void onCreate(Bundle savedInstanceState) {
getActionBar().setDisplayShowTitleEnabled(true);
Make Callback class
package com.yourpackage.view;
public interface HomePageBottomCallback extends IView {
void onTitle(String Title);
}
package com.yourpackage.view;
import android.content.Context;
public interface IView {
Context getContext();
}
implements with HomePageBottomCallback to your main class and implement its method in main class
public class MainActivity extends BaseActivity
implements HomePageBottomCallback{
}
#Override
public void onTitle(String Title) {
TitleSet(Title);
setTitle(Title)
}
in FRAGMENT CAllback used
public HomePageBottomCallback callback;
#Override
public void onAttach( Context context) {
super.onAttach(context);
try {
callback = (HomePageBottomCallback) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement HeadlineListener");
}
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false);
callback.onTitle("Your Page");
}
How can I call a method from fragment activity when my method placed is the Activity?
public class PosMainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trx);
Bundle extras = getIntent().getExtras();
if (extras != null) {
response_message = extras.getString("RESPONSE_MESSAGE");
}
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
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));
}
public void parseJsonResponse(String jsonResponse){
// I parses and adds the value to the text view or button here
try {
JSONObject ResponseHeaderObject = new JSONObject(responseData);
String UIHeader = ResponseHeaderObject.getString("HEADER");
//Set Header Display
headerTextView =(TextView) findViewById(R.id.headerTextView);
headerTextView.setText(UIHeader);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
#Override
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
parseJsonResponse(response_message);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
//Switch to different layout accordingly
switch (getArguments().getInt(ARG_SECTION_NUMBER))
{
case 1: {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
break;
}
case 2: {
rootView = inflater.inflate(R.layout.fragment_receipt, container, false);
break;
}
}
return rootView;
}
}
}
When I place the parseJsonResponse in onViewCreated() method - I get the following error:
non static field cannot be referenced from a static context android
parseJsonResponse() is in my Activity class and I cannot change that to static method.
What I can do in this case?
Solution:
Call method of Activity from fragment
((YourActivityName)getActivity()).addUserLineInfoFragment();
Caution: This may cause leak somethimes. Hence,
Call method of fragment from Activity
1. Create Interface
public interface OnButtonListener
{
void onButtonClick();
}
2. Init in Activity
protected OnButtonListener onActionButtonListener;
public void setOnButtonListener(OnButtonListener actionButtonListener)
{
this.onActionButtonListener = actionButtonListener;
}
3. In Activity, click event when this action need to perform
this.onActionButtonListener.onButtonClick();
4. Implement listener(OnButtonListener) in Fragment
#Override
public void onButtonClick(){}
5. In fragment onCreateView
((YourActivityName) getActivity()).setOnButtonListener(this);
Source: Refer This
I create simple project using actionbar ,i've one class and one fragment class, i define custome actionbar in class, and my problem, how to call method actionbar in fragment class from class,
this code like below :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holder);
fragmentArray = new ConferenceFragment[8];
// Load main fragment
fragment = new HomeFragment();
fragmentArray[0] = fragment;
currentFragmentIndex = 0;
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.holder, fragment).commit();
// initMenuBar();
}
public void initMenuBar(){
ActionBar actionBar = getActionBar();
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionBar.setCustomView(R.layout.menu_bar);
ImageButton buttonSideMenu = (ImageButton) findViewById(R.id.bt_menu);
buttonSideMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
toggle();
// Toast.makeText(getApplicationContext(), "Clicked!",Toast.LENGTH_LONG).show();
}
});
actionBar.show();
}
// fragment class
public class HomeFragment extends Fragment{
View v;
MainActivity mainactivity;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
mainActivity.initMenuBar(); // ERROR IN THIS LINE
super.onCreateView(inflater, container, savedInstanceState);
v = inflater.inflate(R.layout.home_fragment, container, false);
return v;
}
}
ActionBar is traditionally the part of Activity and is available to activity only. You can get Activity instance by calling getActivity() from fragment and cast it to your activity then call public method to do whatever you want.
But the better option is to use ToolBar explained here support library v7
You need to get your MainActivity's context reference in your fragment to access activity's method.
Try this.
public class HomeFragment extends Fragment{
View v;
Context mContext;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreateView(inflater, container, savedInstanceState);
v = inflater.inflate(R.layout.home_fragment, container, false);
mContext = getActivity();
((MainActivity) mContext).initMenuBar();
return v;
}
}
I have a NavigationDrawer with an Actionbar and a Fragment. My Fragment has a ScrollView with a RelativeView I am trying to add other Views to this RelativeView. I end up with a NullExceptionPointer in the addView() method which means one of my objects is null, but I cannot figure it out - though it works if I call addView() in the Fragment class. My question is why is it the way it is. Why do I end up with a NPE. I just want to understand what I am doing wrong.
With further research it turns out that mContainer is null. But I inflate fragment_main then why is it still null?
my simplified MainActivity :
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private ViewGroup mContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getLayoutInflater.inflate(R.layout.fragment_main);
mContainer = (ViewGroup) findViewById(R.id.main_container);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_add_item:
addItem(); **// NullPointerException**
return true;
}
return super.onOptionsItemSelected(item);
}
public void addItem() { //method responsible for NPE
LayoutInflater layoutInflater = this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.ingredient, null);
final ViewGroup newView =(ViewGroup) layoutInflater.inflate(R.layout.list_example,mContainer,false);
mContainer.addView(newView, 0);
}
public static class PlaceholderFragment extends Fragment {
private View nicView;
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(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, final ViewGroup mainContainer = (ViewGroup) rootView.findViewById(R.id.main_container);
final View nicView = View.inflate(getActivity(),R.layout.nicotine, null);
mainContainer.addView(nicView, 0);
return rootView;
}
Any help is appreciated, thanks
Hi shouldn't your stack trace show were the NPE occurs ?
Is it possible that the layout inflater is null?
They way i normaly set my inflater is by
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
I am having an issue getting the view to change on a tabhost - when I select a tab the content stays blank.
From what I can tell, onCreateView is not being called on the child Fragments. onMenuCreate runs fine because the menu changes like it is supposed to.
public class PatientTabFragment extends Fragment {
private FragmentTabHost mTabHost;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager());
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Info"),
NewPatientFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Notes"),
NoteListFragment.class, null);
return mTabHost;
}
#Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
}
according to the docs:
Special TabHost that allows the use of Fragment objects for its tab
content. When placing this in a view hierarchy, after inflating the
hierarchy you must call setup(Context, FragmentManager, int) to
complete the initialization of the tab host.
(emphasis mine)
So I suggest somethong like this:
public class PatientTabFragment extends Fragment {
private FragmentTabHost mTabHost;
private boolean createdTab = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager());
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Info"),
NewPatientFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Notes"),
NoteListFragment.class, null);
return mTabHost;
}
public void onResume(){
if (!createdTab){
createdTab = true;
mTabHost.setup(getActivity(), getActivity().
getSupportedFragmentManager());
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
}
Now we can use TabLayout and ViewPager do those things.This is a good guide to use it.Here is my code:
viewPager=(NonSwipeableViewPager)view.findViewById(R.id.circleresdyn_viewpager);
tabLayout=(TabLayout)view.findViewById(R.id.circleresdyn_tablayout);
if (viewPager != null) {
Adapter adapter = new Adapter(((AppCompatActivity)activity).getSupportFragmentManager());
ContentFragment con=new ContentFragment();
con.setArguments(bundleForFramgnet);
MemberFragment memberFragment=new MemberFragment();
memberFragment.setArguments(bundleForFramgnet);
CirResDynTileFragment cirResDynTileFragment=new CirResDynTileFragment();
cirResDynTileFragment.setArguments(bundleForFramgnet);
adapter.addFragment(cirResDynTileFragment, "Tab1");
adapter.addFragment(con, "Tab2");
adapter.addFragment(memberFragment, "Tab3");
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);
tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).select();
}
Check this peace of code. It may help you:
import android.app.Fragment;
public class Change_password extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.change_password, container,false);
setTabs();
return rootView;
}
private void setTabs() {
try {
addTab("Airlines", R.drawable.tab_home, HomeActivity_bkp.class);
addTab("Advance Search", R.drawable.tab_search,
AdvanceSearchAcitivty.class);
addTab("Booking", R.drawable.tab_home, Booking.class);
addTab("Settings", R.drawable.tab_search, SettingAcitivty.class);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
// TODO: handle exception
}
}
private void addTab(String labelId, int drawableId, Class<?> c) {
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(
R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}