Hawkridge Hawkridge - 1 month ago 9
Android Question

Android - set button text from Fragment in Activity

I created new project with Navigation Drawer Activity template in Android Studio 2.2.2. I decided to use FrameLayout, so as i click on navigation menu item, new fragment loads.

In my content_main.xml i have FrameLayout element like this:

<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>


That is Frame where the content will be shown.

Then i have layout fragment_one.xml and its class FragmentOne and they look like this:

fragment_one.xml

<Button
android:text="Default Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mybutton" />




FragmentOne class

public class FragmentOne extends Fragment {

Button btn;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
btn = (Button) view.findViewById(R.id.mybutton);
return view;
}

public void changeBtnText(String txt)
{
btn.setText(txt);
}
}


In MainActivity's onCreate() method i have code:

FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.content_frame, new FragmentOne()).commit();

FragmentOne fragment_obj = (FragmentOne)getSupportFragmentManager().
findFragmentById(R.id.frOne);
fragment_obj.changeBtnText("Changed text");


Here i get error:


Attempt to invoke virtual method 'void com.example.user.myapplication.FragmentOne.changeBtnText(java.lang.String)' on a null object reference


How I can change fragment's Button text from Main Activity by using changeBtnText(String txt) method?

Answer

Call changeBtnText(String txt) inside fragment not in the activity.

EDIT:

inside FragmentOne.class

public FragmentOne newInstance(String text) {
    FragmentOne fragmentOne = new FragmentOne ();

    Bundle args = new Bundle();
    args.putInt("text", text);
    fragmentOne .setArguments(args);

    return fragmentOne ;
}

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_one, container, false);
    btn = (Button) view.findViewById(R.id.mybutton);

    String text = getArguments().getString("text", null);
    changeBtnText(text);

    return view;
}

in the Activity

FragmentManager fm = getSupportFragmentManager();
    fm.beginTransaction().replace(R.id.content_frame, FragmentOne.newInstance("text")).commit();
Comments