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;
}
}
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 want to made a lock screen Button in a Fragment Layout.
I searched some help and found the same, but made using an Activity.
The code is here:
http://karanbalkar.com/2014/01/tutorial-71-implement-lock-screen-in-android/
I don't know how to change it to work in a Fragment?
Please help
My code:
public class Tab1fragment extends Fragment {
/**
* #param args
*/
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.tab1_layout, container, false);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
you have to read more about Fragment: http://developer.android.com/reference/android/app/Fragment.html
first you have to implement View.OnClickListener in your Fragment, then create a View inside onCreateView like :
View rootView = inflater.inflate(R.layout. tab1_layout, container, false);
so your fragment became :
public class Tab1fragment extends Fragment implements View.OnClickListener {
.
.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1_layout, container, false);
mDevicePolicyManager = ...
mComponentName = ...
Button btnEnableAdmin = (Button) rootView.findViewById(R.id.btnEnable);
.
.
btnEnableAdmin.setOnClickListener(this);
.
.
return rootView;
}
public void onClick(View v) {
switch (v.getId()) {
...
}
}
}
NB: I tested this code on my device
I have seen Link1 for this issue but could understand it right. I have a fragment that loads a list. When i click the list item it opens another activity. But i press back button it loads the list again. I want it to be at the same scroll position where it was before. In above mentioned link it specifies to use flag but i haven't got the point.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
android.app.Fragment fragment = new MeFragment();
getFragmentManager().beginTransaction().replace(R.id.layout_FragmentsContainer, fragment).addToBackStack(null).commit();
}
}
public class MeFragment extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_me, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
meLV = (ListView) getView().findViewById(R.id.lv_Inbox);
loadingListProgress = (ProgressBar) getView().findViewById(R.id.progress_LoadingList);
meList = new ArrayList<Message>();
meAdapter = new MessagesListAdapter(getActivity(), meList);
//addFooter();
meLV.setAdapter(meAdapter);
meLV.setOnItemClickListener(this);
pageCount = 0;
loadmoreProgressDialog = new ProgressDialog(getActivity());
loadmoreProgressDialog.setTitle("Please wait ...");
loadmoreProgressDialog.setMessage("Loading more ...");
loadmoreProgressDialog.setCancelable(true);
loadUserMessages();
meLV.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
// TODO Auto-generated method stub
//addFooter();
loadmoreProgressDialog.show();
loadUserMessages();
}
});
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Utils.showToast_msg(getActivity(), "MessageItemClicked");
ReferralDetailFragment fragment = new ReferralDetailFragment();
getFragmentManager().beginTransaction().replace(R.id.layout_FragmentsContainer, fragment).addToBackStack(null).commit();
}
}
public class ReferralDetailFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_referraldetail,container, false);
linkToAcknowledge = (TextView) view.findViewById(R.id.lbl_Link_to_Acknowledge);
return view;
}
}
I implemented a simple solution for this in my app, basically when you press back to go to the fragment again, onCreateView() is called. Here in onCreateView() you have done all initialization, so we change
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_me, container, false);
/*
*Whatever you want to do
*
*/
return view;
}
to:
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
if(view==null){
view = inflater.inflate(R.layout.fragment_me, container, false);
/*
*Whatever you want to do
*
*/
}
else{
((ViewGroup)view.getParent()).removeView(view);
}
return view;
}
Here, we move View view outside and make it a class variable. So if it is the first time the fragment is called, it is null and the initialization occurs, otherwise it goes to else black. Else block is required because onCreateView() adds whatever it returns as a child of the view's parent, so since view is already there, we remove it and onCreateView automatically adds it again.
According to our exchange in the comments, I completely deletde my answer and re-write a new one.
I copy/paste the code from one of my apps and removing the useless things and changing the names. Hope there is not too many typing mistakes, at that it is the minimum required to have it working.
When I pop back to FirstFragment from SecondFragment, the scroll position of FirstFragment is the same as when I clicked an item to load the SecondFragment.
Note that I don't extend FragmentActivity. I have an activity which loads the fragments.
Extend/modify to match your needs.
MainActivity :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
}
}
FirstFragment Class :
public class FirstFragment extends Fragment implements OnItemClickListener {
private ListView mListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.first_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mListView = (ListView) getView().findViewById(R.id.listview_first_fragment);
mListView.setAdapter(mAdapter); // depends on your adapter
mListView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mListView.setItemChecked(position, true);
//in case you need, set the bundle here, for example pass the position
Bundle arguments = new Bundle();
arguments.putInt("position", position);
SecondFragment secondFragment = new SecondFragment();
secondFragment.setArguments(arguments);
getFragmentManager().beginTransaction().replace(R.id.fragment_container, secondFragment).addToBackStack(null).commit();
}
}
SecondFragment Class :
public class SecondFragment extends Fragment {
private Integer mPosition;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.second_fragment_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle arguments = getArguments();
if (arguments == null) {
mPosition= 0;
} else {
mPosition= arguments.getInt("Position");
}
}
}
What you are trying to achieve may be done with help of savedInstanceState. i also had this kind of problem which i resolved by using add() method instead of replace() in transition.
If you can change your method or already not using add() than give it a shot.
and if add() method didn't do the trick then check the implementation of savedInstanceState.
correctly save instance state.
How to save states of fragment views.
I'm new to Android and I'm playing with Fragments, I know that there exist many examples to learn how Fragments work, unfortunately there is not many examples using Nested-Fragments (which are in the same Activity).
This is my code below, ive encountered 2 problems:
The Root Fragment is visible after I add the secondary Fragment.
both Fragment use same design, but when I add the FragmentIi can see the dimensions of the widgets and the position on the screen are not the same.
I Need some feedback how to do it right.
Thank you!
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login,
container, false);
TextView tv = (TextView) rootView.findViewById(R.id.signUpText1);
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.loginViewPlaceholder, new SignupFragment());
ft.commit();
}
});
return rootView;
}
}
public static class SignupFragment extends Fragment {
public SignupFragment() {
// TODO Auto-generated constructor stub
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View signupView = inflater.inflate(R.layout.fragment_signup,
container, false);
return signupView;
}
}
}
The replace method will remove a fragment from the specified container and add the new one its place. In your example, it looks like you are adding the PlaceholderFragment to the container android.R.content and the SignupFragment to the container R.id.loginViewPlaceholder. If you want the SignupFragment to replace the PlaceholderFragment you will have to either use the same container for both, or you will have to do separate remove() and add() calls for your transaction.