Can't change fragment text view from a method - android

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

Related

Cannot resolve symbol in Inflater in findViewById [duplicate]

I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = (ImageView)findViewById(R.id.my_image);
return inflater.inflate(R.layout.testclassfragment, container, false);
}
}
The findViewById method has an error on it which states that the method is undefined.
Use getView() or the View parameter from implementing the onViewCreated method. It returns the root view for the fragment (the one returned by onCreateView() method). With this you can call findViewById().
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
// or (ImageView) view.findViewById(R.id.foo);
As getView() works only after onCreateView(), you can't use it inside onCreate() or onCreateView() methods of the fragment .
You need to inflate the Fragment's view and call findViewById() on the View it returns.
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
}
Inside Fragment class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
// or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
Always remember in case of Fragment that onViewCreated() method will not called automatically if you are returning null or super.onCreateView() from onCreateView() method.
It will be called by default in case of ListFragment as ListFragment return FrameLayout by default.
Note: you can get the fragment view anywhere in the class by using getView() once onCreateView() has been executed successfully.
i.e.
getView().findViewById("your view id");
I realise this is an old question, but the prevailing answer leaves something to be desired.
The question is not clear what is required of imageView - are we passing it back as the view, or merely saving a reference for later?
Either way, if the ImageView is coming from the inflated layout, the correct way to do this would be:
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v;
}
}
Get first the fragment view and then get from this view your ImageView.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
}
Inside Fragment class we get onViewCreated() override method where we should always initialize our views because in this method we get view object. Using this object we can find our views like below:
class MyFragment extends Fragment {
private ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//initialize your view here for use view.findViewById("your view id")
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
You could also do it in the onActivityCreated Method.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
Like they do here: http://developer.android.com/reference/android/app/Fragment.html (deprecated in API level 28)
getView().findViewById(R.id.foo);
and
getActivity().findViewById(R.id.foo);
are possible.
getView() will give the root view
View v = getView().findViewByID(R.id.x);
You can override onViewCreated() which is called right after all views had been inflated. It's the right place to fill in your Fragment's member View variables. Here's an example:
class GalleryFragment extends Fragment {
private Gallery gallery;
(...)
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setAdapter(adapter);
super.onViewCreated(view, savedInstanceState);
}
}
The method getView() wont work on fragments outside OnCreate and similar methods.
You have two ways, pass the view to the function on the oncreate (what means you can only run your functions when the view is being created) or set the view as a variable:
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_contatos, container, false);
}
public void doSomething () {
ImageView thumbnail = (ImageView) rootView.findViewById(R.id.someId);
}
1) first inflate layout of Fragment then you can use findviewbyId .
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);
agreed with calling findViewById() on the View.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) V.findViewById(R.id.my_image);
return V;
}
Note :
From API Level 26, you also don't need to specifically cast the result of findViewById as it uses inference for its return type.
So now you can simply do,
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = view.findViewById(R.id.my_image); //without casting the return type
return view;
}
Use
imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);
imageview = (ImageView) getActivity().findViewById(R.id.imageview1);
it will work
According to the documentation on API level 11
Reference, in Back Stack
http://developer.android.com/reference/android/app/Fragment.html
short code
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
Using getView() returns the view of the fragment, then you can call findViewById() to access any view element in the fragment view.
Try this it works for me
public class TestClass extends Fragment {
private ImageView imageView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
findViews(view);
return view;
}
private void findViews(View view) {
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
1) Declare your layout file.
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
return inflate(R.layout.myfragment, container, false);
}
2)Then, get the id of your view
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView nameView = (TextView) view.findViewById(R.id.textview1);
}
The best way to implement this is as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) rootView.findViewById(R.id.my_image);
return rootView
}
In this way, the rootView can be used for each control defined in the xml layout and the code is much cleaner in this way.
Hope this helps :)
Try This:
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);
return v;
try
private View myFragmentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
myFragmentView = inflater.inflate(R.layout.myLayoutId, container, false);
myView = myFragmentView.findViewById(R.id.myIdTag)
return myFragmentView;
}
Use gradle skeleton plugin, it will automatically generate the view holder classes with the reference to your layout.
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyLayout myLayout = new MyLayout(inflater, container, false);
myLayout.myImage.setImageResource(R.drawable.myImage);
return myLayout.view;
}
}
Now assuming you had an ImageView declared in your my_layout.xml file, it will automatically generate myLayout class for you.
I like everything to be structured. You can do in this way.
First initialize view
private ImageView imageView;
Then override OnViewCreated
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
findViews(view);
}
Then add a void method to find views
private void findViews(View v) {
imageView = v.findViewById(R.id.img);
}
//here you can do it by
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_apple, container,
false);
ist = view.findViewById(R.id.linearLink);
second = view.findViewById(R.id.linearPhone);
return view;
ImageView imageView;
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
imageView = view.findViewById(R.id.my_image);
return view;
}
You can call findViewById() with the Activity Object you get inside your public void onAttach(Activity activity) method inside your Fragment.
Save the Activity into a variable for example:
In the Fragment class:
private Activity mainActivity;
In the onAttach() method:
this.mainActivity=activity;
Finally execute every findViewById through the vairable:
mainActivity.findViewById(R.id.TextView);
Inside onCreateView method
1) first you have to inflate the layout/view you want to add
eg. LinearLayout
LinearLayout ll = inflater.inflate(R.layout.testclassfragment, container, false);
2) Then you can find your imageView id from layout
ImageView imageView = (ImageView)ll.findViewById(R.id.my_image);
3)return the inflated layout
return ll;
You have to inflate the view
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v
}}
There is one more method called onViewCreated.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
}

which method when display dialog show in fragment

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.

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.

How to get an id of a View inside a Fragment

Hi I am trying to get an id of some View in a Fragment from a string, however it doesn't seem to work... Is there a special case for fragments?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View singleplayerView = inflater.inflate(R.layout.singleplayer_tab, container, false);
setupMap();
return singleplayerView;
}
private void setupRank() {
TextView view = (TextView) getByStringId("rank0");
view.setText("hello");
}
private final View getByStringId(final String id) {
return findViewById(getResources().getIdentifier(id, "id", getActivi
ty().getPackageName()));
}
So I am trying to set the textView field rank0 in the layout that is used for my fragment... but right now it gets a NUllPointer because it couldnt find the id
Thank you
you can define your Layout In your onCreateView() inside Fragments like this:
View V = new View(getActivity());
V = inflater.inflate(R.layout.fragment_layout,container, false);
Then
TextView SomeField = (TextView)V.findViewById(R.id.TxtSomeField);
Inside fragment, add getActivity before findViewById:
getActivity().findViewById(...);
Try this,
String id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extra = getArguments();
id = extra.getString("id", "");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_calendar_details, container, false);
Button b = (Button) view.findViewById(id);
return view;
}

Android Fragment Implementation

I am trying to implement Fragments in my Project using the https://github.com/JakeWharton/Android-ViewPagerIndicator plugin.
My Fragment
public final class NearByFragment extends Fragment {
private static String TAG = "bMobile";
public static NearByFragment newInstance(String content) {
NearByFragment fragment = new NearByFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
return inflater.inflate(R.layout.fragment_search_nearby, null);
}
}
Now I want to execute some code like start start a new thread and download a JSON from the server and then assign a list view from the content I download. In fragments we are assigning views in onCreateView. so where should I write the
listview = (ListView) findViewById(R.id.list_items);
((TextView) findViewById(R.id.title_text))
.setText(R.string.description_blocked);
and other code to generate the Fragment view ?
You can search within the view that you just inflated:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
View v = inflater.inflate(R.layout.fragment_search_nearby, null);
listview = (ListView)v.findViewById(R.id.list_items);
((TextView)v.findViewById(R.id.title_text))
.setText(R.string.description_blocked);
return v;
}
You can also use the Fragment.getView() function elsewhere in your code and call that view's findViewById() member.
You can use getActivity().findByView() from the Fragment if you want to have access to the layout elements. Alternatively, you can just put the findByView() call in the main Activity.

Categories

Resources