change custom ActionBar title from fragment in android - android

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");
}

Related

How can I call a method from fragment activity when my method placed is the Activity?

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

Custom Actionbar in fragment android

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;
}
}

getActivity().getActionBar() on first fragment crash

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) {
}
}

Notify from child fragment inside ViewPager to his parent an event

i have a fragment inside a activity, this fragment contains a viewpager, this is the code:
public class RepliesContainerFragment extends Fragment {
#InjectView(R.id.viewPager)
ViewPager pager;
private PagerAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReplyActivity replyActivity = (ReplyActivity) getActivity();
List<Replie> replies = getArguments().getParcelableArrayList("replies");
adapter = new PagerAdapter(replyActivity.getSupportFragmentManager(), replies);
setActionBar();
}
private void setActionBar() {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);
getActivity().getActionBar().setIcon(getResources().getDrawable(R.drawable.ic_back));
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
getActivity().getActionBar().setTitle("Respuestas");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.work_containter_replies, container, false);
ButterKnife.inject(this, view);
pager.setAdapter(adapter);
return view;
}
}
Inside the adapter i had instantiate some fragments like this:
public class ReplyFragment extends Fragment {
#InjectView(R.id.tvQuestion)
TextView tvQuestion;
#InjectView(R.id.frameContainter)
FrameLayout replyContainer;
private ReplyView replyView;
private String question;
private String currentReplie;
private int replieType;
private int questionId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
replieType = getArguments().getInt("replyType");
question = getArguments().getString("question");
questionId = getArguments().getInt("questionId");
currentReplie = getArguments().getString("currentReplie");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.work_reply_fragment, container, false);
ButterKnife.inject(this, view);
initQuestionText();
return view;
}
private void persistReply() {
ReplyActivity replyActivity = (ReplyActivity) getActivity();
if (replyActivity != null) {
//DO SOMETHING
//Notify to adapter from here
}
}
}
}
As you can see, i want to notify to my RepliesContainerFragment and his inside adapter that some event happens and do an action..
How can i do it this?
With broadcastreceivers, with callbacks(Interfaces)..?I am not sure.
The very simple solution for this is to pass a listener instance from your parent fragment to a child fragment. You have to create a listener interface, create an instance of it in your parent fragment, and pass that instance to all your children fragments.
By the way there is a topic regarding this problem in the official tutorial.
Hope this helps.
I think it is easier:
private void persistReply() {
ReplyActivity replyActivity = (ReplyActivity) getActivity();
if (replyActivity != null) {
//DO SOMETHING
RepliesContainerFragment frag = ((RepliesContainerFragment)this.getParentFragment());
frag.getAdapter().notifyDataSetChanged();
}
}
}
and make getter setter for adapter

ViewPager + FragmentPagerAdapter inside a DialogFragment gets "IllegalArgumentException:No view found..."

I am trying to show a FragmentDialog ( created and shown as a dialog NOT added as content in a view hierarchy) where there is a ViewPager whose content is given by a FragmentPagerAdapter (provides Fragments consisting of an image).
The code works perfect when showing ViewPager + FragmentPagerAdapter from a FragmentActivity, but get the following exception when doing it from a FragmentDialog:
"IllegalArgumentException: No view found for id 0x7f040077 for fragment SimpleFragment..."
Here is my code:
A SherlockFragmentActivity with a button to create and show the dialog.
public class BorrameActivity extends SherlockFragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one_act);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
showTheDialog();
}});
}
private void showTheDialog(){
AchGalleryDialog newFragment = AchGalleryDialog.newInstance(achs);
newFragment.show(getSupportFragmentManager(), "dialog");
}
The FragmentDialog:
public class AchGalleryDialog extends DialogFragment{
public AchGalleryDialog(){
}
public static AchGalleryDialog newInstance(){
AchGalleryDialog f = new AchGalleryDialog();
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_user_result, container);
getDialog().setTitle("Hola tronco");
//content to show in the fragments
int[] images = new int[]{R.drawable.d1, R.drawable.d2, R.drawable.d3};
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
MyFragmentAdapter adapter = new MyFragmentAdapter(getFragmentManager(),images);
pager.setAdapter(adapter);
return view;
}
}
This is the very simple MyFragmentPagerAdapter,
I put only the getItem() method, and nullPointer checks:
#Override
public Fragment getItem(int position) {
return MySimpleFragment.newInstance(images[position]);
}
And finally SimpleFragment:
public class SimpleFragment extends Fragment{
int id;
public static SimpleAchFragment newInstance(int imgId){
SimpleFragment f = new SimpleFragment();
Bundle args = new Bundle();
args.putLong(ID_BUNDLE, imgId);
f.setArguments(args);
return f;
}
public SimpleAchFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.id = getArguments() != null ? getArguments().getInt(ID_BUNDLE) : 0;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.simple_fragment, container, false);
FragmentActivity mAct = getActivity();
ImageView img = (ImageView) v.findViewById(R.id.image);
img.setImageDrawable(mAct.getResources().getDrawable(id));
return v;
}
}
More info, if the content passed to the adapter ( an int array with 3 ints) has length zero, then the adapter doesn't try to create any Fragment so dialogs appears correctly but empty (as expected).
The Exception is thrown at SimpleFragment.onCreateView() at the time of inflating.
The id referenced in the exception (as not found) correspond to ViewPager 's id, with is properly defined in R.layout.simple_fragment.
I have try also to build the Dialog with an AlertDialog.builder and also directly with Dialog() contructor, but get the same behaviour.
Try this:
In class AchGalleryDialog
MyFragmentAdapter adapter = new MyFragmentAdapter(getChildFragmentManager(),images);
instead of
MyFragmentAdapter adapter = new MyFragmentAdapter(getFragmentManager(),images);
Because of this:
http://developer.android.com/about/versions/android-4.2.html#NestedFragments
Hope this will help!

Categories

Resources