如何从Android中的另一个片段启用/禁用按钮? [英] How to Enable/ Disable button from another fragment in android?

查看:96
本文介绍了如何从Android中的另一个片段启用/禁用按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,其中包含来自片段编号1的4个片段.当我单击片段1中的按钮时,我想启用片段3上的现有按钮(即禁用).这是我的尝试:片段1:

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

这给我一个错误:

java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'void android.widget.Button.setEnabled(boolean)'

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?

推荐答案

首先,创建一个接口.

UpdateButtonListener.java

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

现在在片段3中,实现类的接口

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

现在是第一个片段.

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

明智地为他人做.

这篇关于如何从Android中的另一个片段启用/禁用按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆