I am new in android and I have been created simple app which have 3 tabs that I build them with Fragment Activity .
in Activities we can use findViewById method . but Fragments don't have this method . how can I access to my views ?
You can call your getAcivity() method within your fragment class to call the context of your activity that is bounded in it and after you can call findViewById();
sample:
public void onViewCreated()
TextView txSample = (TextView)getView().findViewById(R.id.yourid);
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_simple_lights, container, false);
tv = (TextView) rootView.findViewById(R.id.yourid);
return load;
}
You would better do all the view-related operations in onCreateView() and all the functional operations in onActivityCreated()
Related
I have a ConstraintLayout (the child) nested in another ConstraintLayout (the parent). I want to be able to call the child from within my Fragment class, but outside onCreateView. This what I have so far:
public class HomeFragment extends Fragment {
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
HomeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
}
ConstraintLayout MyLayout = (ConstraintLayout) getView().findViewById(R.id.my_layout);
}
Which results in a NullPointerException:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
I even tried declaring a global root variable in the Fragment class and assigning the inflated view result to it, but the problem persists.
I cannot place myLayout inside OnCreateView so I need a solution where I can use it outside of it.
Your issue stems from a misunderstanding about when and for how long a fragment's view exists.
Currently, you are assigning your MyLayout variable during construction of your fragment.
According to the Android documentation on a Fragment's lifecycle a fragment won't have a view associated with it until after onCreateView is called. Later on in the fragment's lifecycle, the view is destroyed when onDestroyView is called.
So, the fragment's view only lives during the intervening time between onCreateView and onDestroyView. If you call getView before onCreateView is called, or after onDestroyView is called, you will get null.
So, if you want to set listeners on views, do so either from onCreateView or onViewCreated and remove them in onDestroyView.
Also, if you want to hold onto your view via a member variable, set it in onCreateView and null it out in onDestroyView and any place you reference it, make sure to check for null first.
You can declare global variable for your view and initialize with a method.
public class HomeFragment extends Fragment {
private ConstraintLayout MyLayout;
private void init(View v) {
MyLayout = v.findViewById(R.id.my_layout);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
init(root);
return root;
}
}
Or you can declare your root and you can find your views with root variable:
public class HomeFragment extends Fragment {
private View root;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
init()
return root;
}
private void init(){
ConstraintLayout MyLayout = root.findViewById(R.id.my_layout);
.
.
.
}
}
I can also suggest you ViewBinding. It simplifies the syntax.
https://medium.com/androiddevelopers/use-view-binding-to-replace-findviewbyid-c83942471fc
But definitely learn about basic Android lifecycle and reasons why you cannot access views before onCreateView.
How are these methods different from each other when trying to get the view?
First:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
listView = view.findViewById(R.id.listview);
return view;
}
Second:
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = getActivity().findViewById(R.id.listview); }
* some say this is used to get activity views but i used it for getting fragment views(which didn't existed in the activity) and it worked fine.
Third:
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
listView = getView().findViewById(R.id.listview);
}
Three methods are good. In the onCreateView you create the view (!), it's the really first time you can use what you inflated. Then onViewCreated is called with the view you returned in the onCreateView, You can directly use the view given as parameter, it is the same the getView() provides. My advice is to initialise your UI variables here
For onActivityCreated, it is the best place to modify your UI elements. It is called when fragment creation is complete and when fragment is re-attached. There you can use the variables you initialised before, without having to get the activity just for that purpose.
Is it possible/recommanded to let different fragments inherit from each other in Android?
What would be the best way to initialize things that are already initialized in the superclass and add things to it ? (-> for example like the normal subclasses that use super() in their constructor and then initializing other objects )
I looked on the internet but i didn't found much information on this.
I know that it's possible to do return super.onCreateView() but you can't initialize other objects/views after that....
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreateView()???
//initialize other objects here
//you have to return a view ...
}
Yes, it is allowed. Why not? For example, if you have a number of Fragments, that display lists, you could put all common methods in FragmentList, and then inherit other fragments, adding only unique methods or overriding the ones from super if needed.
But overriding onCreateView() could raise difficulties in layouts handling. In my recent project I instead created a method inflateFragment() in the super class as follows:
BaseFragment.java
protected View inflateFragment(int resId, LayoutInflater inflater, ViewGroup container) {
View view = inflater.inflate(resId, container, false);
FrameLayout layout = (FrameLayout)view.findViewById(R.id.fragment_layout);
/*
* Inflate shared layouts here
*/
. . .
setHasOptionsMenu(true);
return view;
}
Because of the structure, each and every fragment layout resource is wrapped in a FrameLayout with id = fragment_layout. But you're free to use LinearLayout or whatever parent view you need.
And then in inherited fragments:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflateFragment(R.layout.my_fragment, inflater, container);
/*
* Do things related to this fragment
*/
...
return view;
}
Here's my code in the main activity don'tn know why error in findViewById occurs
.. this is just my first time in JSON paarsing .
public class HomeFragment extends Fragment{
public HomeFragment(){}
View rootView;
ListView list;
ActorsAdapter adapt;
ArrayList<Actors> actorslist;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
list = (ListView)findViewById(R.id.listFeeds);
actorslist = new ArrayList<Actors>();
return rootView;
new ActorsAsynTask().execute("http://jcasim.5gbfree.com/Project/login.php");
}
listFeeds It's a component I'm pretty sure is a component that lives in your fragment. Since you haven't return the root view yet, the findViewById is not going to find it. you have to wait until it's on screen to ask for it using findViewById (in onStart() method) or ask it form the root view before you return it.
it would be list = (ListView)rootView.findViewById(R.id.listFeeds);
The View of the Fragment is not set before the onCreateView() returns. Therefore the findViewById() tries to find the specified R.id.listFeedsfrom a null reference.
Try this instead list = (ListView)rootView.findViewById(R.id.listFeeds);
I am new in Android programming.
I created the main Activity of my app style google shop ussing ActionBarSherlock and a NavigationTabs, with fragments, each referencing another activity (Fragment 1 Fragment 2, etc) and each fragment inflating a layout.
However, I'm used to create layouts in xml and then customize them in java. To put a different text depending on the time of day, or according to some data in a database, giving function to buttons, etc.. But in a Fragment Class, I can not even use setContentView to work with each text or button, and set the context for using my database is giving me problems.
How I can customize a xml layout in a fragment?
Or what would be the right thing to do?
Here my Fragment:
public class Fragment1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.menu, container, false);
}
This is more simple then you think. onCreateView instanciate au returns the view for your Fragment. As you said, in a simple Activity you set (and instanciate) the view with setContentView() and then you get your Views with findViewById().
findViewById() asks for the view to return the view item that you want, you can call it from your view before returning it. Like this:
public class Fragment1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.menu, container, false);
// For example, getting a TextView
TextView tv = (TextView) v.findViewById(R.id.myTextView);
// do your job
return v;
}
so far so good, you just need to use the view you are inflating to get everything.
here is an example
View v = inflater.inflate(R.layout.menu, container, false);
Button b = (Button)v.findViewById(r.id.button1);
return v;
inside onActivityCreated you could use:
View mView = getView();
TextView textView = (TextView) view.findViewById(R.id.theIdOfTextView);
where theIdOfTextView is declared inside R.layout.menu.
getView() returns the View you inflated inside onCreateView. You use it only after onCreateView has been executed