我正在尝试为我的应用程序添加基本设置。如果未选中复选框,我想在我的一项活动中更改 EditText 的提示。
首选项.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="PREF_SHOW_UNITS"
android:id="@+id/Check1"
android:title="Show units in Kinematics"
android:defaultValue="true" >
</CheckBoxPreference>
</PreferenceScreen>
设置活动.java:
package com.supermath.jacobgb24.supermath;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import static com.supermath.jacobgb24.supermath.R.xml.preferences;
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(preferences);
}
}
我正在尝试将更改添加到以下位置的代码:
public class Kinematics extends ActionBarActivity {
static EditText tval, aval, vval, xval;
static double a, t, x, v;
static DecimalFormat fmt = new DecimalFormat("###,###.###");
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.klayout);
CheckBox cb1 = (CheckBox) findViewById(R.id.Check1);
tval = (EditText) findViewById(R.id.time);
aval = (EditText) findViewById(R.id.accel);
vval = (EditText) findViewById(R.id.velocity);
xval = (EditText) findViewById(R.id.xpos);
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton checkbox, boolean isChecked) {
if (isChecked) {
tval.setHint("YAY");
} else {
tval.setHint("UNYAY");
}
}
});
}
<小时 />解决
由于我使用的是首选项,因此我需要以下代码:
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean disp = prefs.getBoolean("PREF_SHOW_UNITS", true);
if(disp)
tval.setHint("t(s)");
tval.setHint("t(s)");
else if(!disp)
tval.setHint("UNYAY");
您可以通过以下方式更改复选框选中的编辑文本的提示:
your_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton checkbox,
boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked)
{
your_edittext.setHint(textonChecked);
}
else
{
your_edittext.setHint(textonUnchecked);
}
}
});
//Get EditText
EditText editText1 = (EditText) findViewById(R.id.editText1);
//Get Checkbox
CheckBox cb1 = (Checkbox) findViewById(R.id.checkBox1);
//Add Listener to Checkbox
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
//Set a hint to EditText
editText1.setHint("This is a hint!");
}
}
});