我有一个活动,其中包含来自片段编号1的4个片段我想在片段1中单击按钮时启用片段3上的现有按钮(即禁用)。这是我的尝试:
片段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)”
如何访问按钮并正确更改其启用状态?
最佳答案
首先,创建一个界面。
UpdateButtonListener.java
public interface UpdateButtonListener {
void onUpdate(boolean status);
}
现在在片段3中,实现类的接口
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);
}
同样为他人做。