我在下面有两个活动。看我的代码...
SettingsActivity.java
public class SettingsActivity extends AppCompatPreferenceActivity {
static CheckBoxPreference checkBoxPreference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
checkBoxPreference = (CheckBoxPreference)findPreference("checkPref");
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (SettingsActivity.checkBoxPreference.isChecked()){
Toast.makeText(MainActivity.this, "Checked", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Not Checked", Toast.LENGTH_SHORT).show();
}
} catch (Exception e){
Toast.makeText(MainActivity.this, "Failed to query", Toast.LENGTH_SHORT).show();
}
}
});
}
}
因为我在这里使用了Try-Catch,所以它没有崩溃。但每次我点击按钮时,它都会显示“查询失败”。
这里有什么问题?请帮忙!!!