which method when display dialog show in fragment - android

I opened dialog in a fragment and when come back to fragment, my fragment's view is null Object.
when the dialog is displaying which lifecycle method fragment is calling?
public class MyFragment extends Fragment{
TextView textView;
View view;
FloatingActionButton actionButton;
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_read, container, false);
textView = view.findViewById(R.id.txtSaved);
actionButton = view.findViewById(R.id.floatingActionButton);
actionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogSearch search = new DialogSearch();
search.show(getActivity().getSupportFragmentManager(),"MyDialog");
}
});
return view;
}
}

The problem is the dialog is being showned in the onCreateView life cycle, that is why is the Fragment view is null. You have to do it inside the onViewCreated method.
#Override
public View onViewCreated(View view, Bundle savedInstanceState) {
//Work here, the view argument in the method is the view inflated in the onCreateView method
});

Make a small change,
public class MyFragment extends Fragment{
TextView textView;
View view;
FloatingActionButton actionButton;
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_read, container, false);
textView = view.findViewById(R.id.txtSaved);
actionButton = view.findViewById(R.id.floatingActionButton);
actionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogSearch search = new DialogSearch();
search.show(getActivity().getSupportFragmentManager(),"MyDialog");
}
});
return view; / Add this line -------
}
}
You need to return view
when the dialog is displaying which lifecycle method fragment is calling?
onPause() of fragment gets called.

Related

Can't change fragment text view from a method

I'm trying this simple method to change a fragment text view but the app crashes every time I try to open the activity of the fragment with this fragment code
public class FragmentContrat extends Fragment {
public FragmentContrat() {}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contrat_fragment, container, false);
update();
return view;
}
public void update() {
TextView textView = (TextView)getView().findViewById(R.id.souscripteur_txt);
textView.setText("milan");
}
however it works fine and the TextView change when I put the same code in onCreateView like this :
public class FragmentContrat extends Fragment {
public FragmentContrat() {}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contrat_fragment, container, false);
TextView textView = (TextView)view.findViewById(R.id.souscripteur_txt);
textView.setText("milan");
return view;
}
the activity code :
public class DetailsContrat extends AppCompatActivity {
TabLayout details_tab;
AppBarLayout details_bar;
ViewPager details_pager;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_contrat);
Intent i = getIntent();
String client_id = i.getStringExtra("client_id");
details_tab=(TabLayout)findViewById(R.id.details_tab);
details_bar=(AppBarLayout) findViewById(R.id.details_bar);
details_pager=(ViewPager)findViewById(R.id.details_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
FragmentContrat fragmentContrat = new FragmentContrat();
FragmentVehicule fragmentVehicule = new FragmentVehicule();
FragmentGaranties fragmentGaranties = new FragmentGaranties();
adapter.AddFragment(fragmentContrat,"MON CONTRAT");
adapter.AddFragment(fragmentVehicule,"MA VOITURE");
adapter.AddFragment(fragmentGaranties,"MES GARANTIES");
details_pager.setAdapter(adapter);
details_tab.setupWithViewPager(details_pager);
}
}
In onCreateView you are creating and the fragment's view. So if you call getView(), to get the fragment view you will get null, because you haven't yet returned the just created view.
You can:
Use the newly-created view similarly to what #Sanjaysinh's is recommending
Avoid setting your text in onCreateView and set it in onViewCreated(View view, Bundle savedInstanceState), that is called after the view has been created (docs)
I think you need to pass your view in update method
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contrat_fragment, container, false);
update(view);
return view;
}
public void update(View view) {
TextView textView = (TextView)view.findViewById(R.id.souscripteur_txt);
textView.setText("milan");
}

How to make BottomSheetDialogFragment cover the full screen?

I'm using BottomSheetDialogFragment to show some data.But when I'm starting the fragment it's appearing 50% of the screen .So, my question is how to make it full screen when it shows.
BottomSheetDialogFragment Code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bot_frag, container, false);
TextView tv = v.findViewById(R.id.textVi);
back=v.findViewById(R.id.back_of_bot);
back.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
}
);
return v;
}
You can use dialog fragments, plz refer this:
public class DialogFragments extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
View view = inflater.inflate(R.layout.dialog_dialogfragment_layout, null);
getDialog().setTitle("Title");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
getDialog().getWindow().setGravity(Gravity.BOTTOM);
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, (int) (metrics.heightPixels * 0.30));// here i have fragment height 30% of window's height you can set it as per your requirement
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogAnimationUpDown;
}
and when you want to open,open Bottomsheet dialog like this way :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bot_frag, container, false);
TextView tv = v.findViewById(R.id.textVi);
back=v.findViewById(R.id.back_of_bot);
back.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getFragmentManager();
DialogFragments dialogFragment = new DialogFragments(this);
dialogFragment.show(fm, "Bottomsheet Fragment");
}
}
);
return v;
}
You have to apply this style to you BottomSheetDialogFragment
android.R.style.Theme_Material_Light_NoActionBar_Fullscreen

Android Fragment Null pointer exception

I am learning android developing(novice).I want to add a fragment to the mainActivity with a textview and change the text. This code works perfectly:
public class Fragment1 extends Fragment {
//#Nullable
//#Override
TextView textt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
((TextView)view.findViewById(R.id.textview)).setText("some text");
return view;
}
}
But this codes invokes null pointer exception:
public class Fragment1 extends Fragment {
//#Nullable
//#Override
TextView textt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
textt = (TextView)view.findViewById(R.id.textview);
return view;
}
public void updateText() {
textt.setText("some text");
}
}
and:
public class Fragment1 extends Fragment {
//#Nullable
//#Override
View view;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_fragment1, container, false);
return view;
}
public void updateText() {
((TextView)view.findViewById(R.id.textview)).setText("some text");
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment1 frg1 = new Fragment1();
ft.replace(R.id.fragment_container, frg1);
ft.addToBackStack(null);
ft.commit();
frg1.updateText();
}
}
why these codes providing different outcome?
my project
frg1.updateText(); is called before the onCreateView lifecycle method of your fragment is called.. You should call the method after you set
textt = (TextView)view.findViewById(R.id.textview);
View view = inflater.inflate(R.layout.fragment_fragment1, container, false);
textt = (TextView)view.findViewById(R.id.textview);
this.updateText();//here
return view;
Check out fragment lifecycle docs regarding onCreateView
The system calls this when it's time for the fragment to draw its user interface for the first time.
This will happen when fragment is loaded not when it is created in your activity.
Here, the textview is not created when you call the updateText function.
Do such calls inside your fragment. Not on the activity which houses the fragment.

Maintain fragment's view state

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.

Android ImageButton worked well in Activity. It doesn't work in Fragment

I'm trying to convert a layout so that it will include fragments.
One of the views is an ImageButton that has a listener.
The code worked fine as an Activity but makes trouble as a Fragment...
First problem was that I couldn't use findViewById,
but I was able to find the answer for that here and fixed it with getView().
I can't find an answer to the second problem...
after I declared:
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
I want to set an on click listener:
camBt.setOnClickListener(listener);
But it keeps acting like the ImageButton (camBt) doesn't exist...
I don't even know what's the problem... it worked fine in the Activity...
Here's the full code.
Many thanks!
public class CameraFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.camera_fragment, container, false);
return V;
}
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
camBt.setOnClickListener(listener);
ImageButton.OnClickListener listener = new ImageButton.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Camera.open().getParameters();
}
};
}
Move
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
camBt.setOnClickListener(listener);
inside onCreateView().
Like
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.camera_fragment, container, false);
// Here it is
ImageButton camBt = (ImageButton)v.findViewById(R.id.button1);
camBt.setOnClickListener(listener);
return v;
}
And one more thing you need to understand that variable name should starts with small letter. So you should use View v instead of View V.
You should add
ImageButton camBt = (ImageButton)getView().findViewById(R.id.button1);
camBt.setOnClickListener(listener);
inside onCreateView() like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.camera_fragment, container, false);
ImageButton camBt = (ImageButton)v.findViewById(R.id.button1);
camBt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
return V;
}
public class CameraFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.camera_fragment, container, false);
ImageButton camBt = (ImageButton)V.findViewById(R.id.button1);
ImageButton.OnClickListener listener = new ImageButton.OnClickListener()
{
#Override
public void onClick(View arg0)
{
Camera.open().getParameters();
}
};
camBt.setOnClickListener(listener);
return V;
}
}

Categories

Resources