How to Enable/ Disable button from another fragment in android?

我们两清 提交于 2020-01-11 12:07:11

问题


i have an activity with 4 fragments from fragment number 1 I want to enable an existing button (that is disable) on fragment 3, when i click in my button in fragment1. this is my attempt: fragment 1:

public class FragmentEvolucion  extends Fragment {
//btnGuardar is in fragment1, the others are in fragment 3 and 4
 Button btnGuardar, btnHabilitarMed, btnHabilitarImc;

  @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_evolucion, container, false);
    btnGuardar=(Button)rootView.findViewById(R.id.btnGuardarEvolucion);
    btnHabilitarMed=(Button)rootView.findViewById(R.id.btnGuardarMedicacion);
    btnHabilitarImc=(Button)rootView.findViewById(R.id.btnGuardarDiagnostico);

   btnGuardar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btnHabilitarMed.setEnabled(true);
            btnHabilitarImc.setEnabled(true);
  }
    });

this give me an error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference

How can i access the button and change it status enabled correctly?


回答1:


First of all, create a interface.

UpdateButtonListener.java

public interface UpdateButtonListener {
    void onUpdate(boolean status);
}

Now in fragment 3, implement interface to class

public class Fragment3 extends Fragment implements UpdateButtonListener{

public static UpdateButtonListener updateButton;

@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment3, container, false);
        updateButton = this;
        return view;
         }

    @Override
    public void onUpdate(boolean status) {
        // here set the functionality of button whether to disable or not .
        if(status){
        btnHabilitarMed.setEnabled(true);
        btnHabilitarImc.setEnabled(true);
        }
    }
 }

Now in first fragment.

btnGuardar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Fragment3.updateButton.onUpdate(true);
  }

Like-wise do for other's.



来源:https://stackoverflow.com/questions/45391856/how-to-enable-disable-button-from-another-fragment-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!