下面是如何實現這一目標的工作示例。活動:
public class MainActivity extends AppCompatActivity {
ToggleFragment toggleFragment;
Button updateStatusButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
updateStatusButton = (Button) findViewById(R.id.updateStatusButton);
toggleFragment = ToggleFragment.newInstance();
getSupportFragmentManager().beginTransaction()
.replace(R.id.main_frame, toggleFragment, "ToggleFragment")
.commit();
updateStatusButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean buttonsChecked = toggleFragment.areToggleButtonsChecked();
Toast.makeText(MainActivity.this, String.format("Toggle buttons checked: %s", buttonsChecked), Toast.LENGTH_LONG).show();
}
});
}
}
和碎片:
public class ToggleFragment extends Fragment {
ToggleButton toggleButton1;
ToggleButton toggleButton2;
ToggleButton toggleButton3;
public static ToggleFragment newInstance() {
Bundle args = new Bundle();
ToggleFragment fragment = new ToggleFragment();
fragment.setArguments(args);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.toggle_fragment, container, false);
toggleButton1 = (ToggleButton) view.findViewById(R.id.toggleButton1);
toggleButton2 = (ToggleButton) view.findViewById(R.id.toggleButton2);
toggleButton3 = (ToggleButton) view.findViewById(R.id.toggleButton3);
return view;
}
public boolean areToggleButtonsChecked() {
return toggleButton1.isChecked()
&& toggleButton2.isChecked()
&& toggleButton3.isChecked();
}
}
它甚至有可能叫 「toggleFragment.toggleButton1.isChecked()」 的活動?即使我們將Buttons公開爲片段,我也不認爲這會起作用。我剛剛證實,並沒有奏效。我錯過了如何從活動中實例化toggleFragment的問題 –
關於第二條建議,我如何從活動中調用此函數。那就是我想要的布爾返回 –
我剛剛編輯了一個工作示例的答案,在我的手機上進行了測試。 – Tharkius