Android get view of fragment in activity [duplicate] - android

This question already has answers here:
findViewById in Fragment
(37 answers)
Closed 2 years ago.
I have an activity, let's call it A, and it launches a fragment like so:
remoteFragment = new RemoteFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout_remote_activity, remoteFragment)
.commit();
my remoteFragment looks something like this:
public Button okBtn;
public RemoteFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_remote, container, false);
okBtn= view.findViewById(R.id.okBtn);
return view;
}
public RemoteLayoutView getOkBtn() {
return okBtn;
}
and in my activity I am trying to get it like so:
Button okBtnMessageNotWorking = remoteFragment.getOkBtn();
but okBtnMessageNotWorking is always null.
my question is how can I get the view objects from the fragment inside my activity?

Here, you are trying to find the view from layoutOnTopScrollview. Instead you should find the okBtn from inflated view. Please change code as below:
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_remote, container, false);
okBtn= view.findViewById(R.id.okBtn);
return view;
}
Also, make sure that you are calling this method once the fragment is created.

Related

Fragment not retaining EditText value after screen rotation [duplicate]

This question already has answers here:
How to retain EditText data on orientation change?
(12 answers)
Closed 5 years ago.
I have already posted this question once and even tried all possible solutions. So please, if are going to downvote, at least provide the correct answer because I have tried out many solutions and nothing is working out.
In my app, I have an EditText inside the fragment which on orientation change, looses its value.One more thing, I am using different layouts for different orientations. Is there any way to retain the fragment data? I am again mentioning "Fragment data".Please find my Fragment code below for further reference.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("fname",etxt_firstname.getText().toString());
outState.putString("lname",etxt_lastname.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// retain this fragment
setRetainInstance(true);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(savedInstanceState!= null)
{
etxt_firstname.setText(savedInstanceState.getString("fname"));
etxt_lastname.setText(savedInstanceState.getString("lname"));
}
}
Inside OnCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
shrp_sharedpreferences = myContext.getSharedPreferences("shrp", Context.MODE_PRIVATE);
View view = null;
if(!isTablet(myContext))
{
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
view = inflater.inflate(R.layout.fragment_home_landscape, container, false);
}
else
{
view = inflater.inflate(R.layout.fragment_home, container, false);
}
}
else
{
view = inflater.inflate(R.layout.fragment_home, container, false);
}
Even though the fragment itself is retained, its view is destroyed when device is rotated in onDestroyView() (You should also clear any references to views there to prevent leaking old orientation).
Trying to restore text in onActivityCreated() does nothing because you're referencing views from old orientation, and they aren't used anymore.
When fragment is reattached (in Activity created for new orientation), new View is created in onCreateView() - this is where you can use savedInstanceState or any fragment fields to restore views to previous state:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// (...) your layout inflation and view binding logic...
if(savedInstanceState != null){
etxt_firstname.setText(savedInstanceState.getString("fname"));
etxt_lastname.setText(savedInstanceState.getString("lname"));
}
// return view you inflated
}

how to call Two fragments in an activity on item click

I am developing an application where i need to call two fragments on an activity replacing another fragment,one of the fragment will contain a Form and another fragment will contain another Form ,i don't have any idea how to do this,so any suggestion will be cordially appreciated,thanks in advance....
I want to replace Form on Click button. by R&D i come to know at this point i need to use to fragment with two layout each layout will contain Forms.
Main Activity.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Fragment 1.
public class Fragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment1, container, false);
}
Fragment 2.
public class Fragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment2, container, false);
}
}
You can try like this
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.add(Home.newInstance(),"First");
ft.add(Second.newInstance(),"Second");
ft.commit();
So here you are added multiple fragment into the stack
If you are trying to replace Fragment1 with Fragment2, you replace the fragment.
https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#replace(int,%20android.support.v4.app.Fragment)

How to set the right fragment to replace.

I’m doing a navigation drawer in my android app. On my onNavigationDrawerItemSelected function i try on item select to change the current fragment into a new one. The problem is that when I change the current fragment its take the initial status of it. maybe because i'm doing this way
fragmentManager.beginTransaction()
.replace(R.id.cont, new SessionsFragement())
.commit();
I declare a new instance of my fragment and i think it’s normal, its display me the initial status of the thing. On my fragment i've try to set a textView to see if i will say it when i call the fragement from tha navigation drawer but it's not the case.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_spot, container, false);
tata = (TextView) v.findViewById(R.id.tata);
tata.setText("karim");
return inflater.inflate(R.layout.fragment_spot, container, false);
}
So please can anyone help me to fix this.
In the snippet you posted you are inflating again the view. You should return the one you modified
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_spot, container, false);
tata = (TextView) v.findViewById(R.id.tata);
tata.setText("karim");
return v;
}

How to set data to layout inflated by a fragment

I have a FragmentActivity which sets a main layout with 3 tabs. Each tab has it's own fragment which inflates is own layout into main layout.
For example, one of the three Fragments:
public class Fragment1 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
return inflater.inflate(R.layout.fragment1, container, false);
}
}
When I add all the fragments and connect them with tabs everything works. When I click on tab1, layout of the Fragment1 shows, when I click on Tab2, layout of the Fragment2 shows.
The problem is that when I want to change something in that inflated layout (for example execute setText to textView in fragment1 layout), I receive a NullPointerException in that line and application stops.
This doesn't work:
TextView test = (TextView) findViewById(R.id.fragmentOneText1);
test.setText("Test text!");
How to set data to inflated layout?
You have to inflate your fragment specific layout first by using LayoutInflater and map the control in your Fragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.R.layout.fragment1, container, false);
TextView text = (TextView) fragmentView.findViewById(R.id.fragmentOneText1);
mTextNoResult=(TextView)fragmentView.findViewById(R.id.text_noresult);
return fragmentView;
}

Set new layout in fragment

I'm trying to change the layout of a fragment during runtime under a particular condition.
The initial layout in inflated within the onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.cancel_video, null);
}
Then sometime later within the fragment code I would like to replace the initial layout with some other layout.
I've tried a few things so far; this is the latest that I have:
private void Something(){
if(checkLicenseStatus(licenseStatus, statusMessage)){
View vv = View.inflate(getActivity(), R.layout.play_video, null);
//more code
}
}
How can I accomplish this?
You cannot replace the fragment's layout once it is inflated. If you need conditional layouts, then you either have to redesign your layout and break it down into even smaller elemens like Fragments. Alternatively you can group all the layout elements into sub containers (like LinearLayout), then wrap them all in RelativeLayout, position them so they overlay each other and then toggle the visibility of these LinearLayouts with setVisibility() when and as needed.
Yes, I have done this in following way. When I need to set a new layout(xml), the following code snippet should be executed.
private View mainView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerObject, Bundle savedInstanceState){
super.onCreateView(inflater, containerObject, savedInstanceState);
mainView = inflater.inflate(R.layout.mylayout, null);
return mainView;
}
private void setViewLayout(int id){
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mainView = inflater.inflate(id, null);
ViewGroup rootView = (ViewGroup) getView();
rootView.removeAllViews();
rootView.addView(mainView);
}
Whenever I need to change the layout I just call the following method
setViewLayout(R.id.new_layout);
Use a FragmentTransaction through the FragmentManger
FragmentManager fm = getFragmentManager();
if (fm != null) {
// Perform the FragmentTransaction to load in the list tab content.
// Using FragmentTransaction#replace will destroy any Fragments
// currently inside R.id.fragment_content and add the new Fragment
// in its place.
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new YourFragment());
ft.commit();
}
The code for the class YourFragment is just a LayoutInflater so that it returns a view
public class YourFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment, container, false);
return view;
}
}
I will change whole layout. You can change only a specific portion of your layout.
Add a root FrameLayout in your_layout.xml, it contains nothing.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fl_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Set your content in the java code.
ViewGroup flContent = findViewById(R.id.fl_content);
private void setLayout(int layoutId) {
flContent.removeAllViews();
View view = getLayoutInflater().inflate(layoutId, flContent, false);
flContent.addView(view);
}
You can change layoutId free at some point.
If you have some listeners, you must set again.

Categories

Resources