【发布时间】:2015-03-24 10:10:45
【问题描述】:
嗨,在片段中使用 OnCheckedChanged 获取复选框的值,但它不起作用,就像我在检查 CheckBox 时没有调用该方法一样。下面是它的实现代码。
CheckBox 使用方式的 XML 文件。
<CheckBox
android:id="@+id/cbDefault"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".2" />
片段的Java代码如下
import android.widget.CompoundButton.OnCheckedChangeListener;
public class ProfileFrag extends AbsFragment implements OnCheckedChangeListener {
private EditText defaultIdText;
private EditText customText;
private EditText randomText;
private TextView phoneText;
private Button setButton;
protected ProfileUpdate profUpdate;
protected String sDefaultId;
protected String sCustomId;
protected String sRandomId;
protected String sPhoneId;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View profView = inflater.inflate(R.layout.intermediate_screen,
container, false);
defaultIdText = (EditText) profView.findViewById(R.id.etDefault);
customText = (EditText) profView.findViewById(R.id.etCustom);
randomText = (EditText) profView.findViewById(R.id.etUname);
phoneText = (EditText) profView.findViewById(R.id.etPhoneNumber);
return profView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
mSharedData = new SharedData(getActivity());
//
// phoneNumber = DeviceIdGen.DevicePhoneNum(getActivity());
phoneText.setText(mSharedData.getPhNum());
randomText.setText(mSharedData.getRandomId());
customText.setText(mSharedData.getCustomId());
defaultIdText.setText(mSharedData.getDefaultId());
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
switch (buttonView.getId()) {
case R.id.cbDefault:
sDefaultId = defaultIdText.getText().toString();
mSharedData.setUniqueid(sDefaultId);
mSharedData.commit();
break;
case R.id.cbCustom:
sCustomId = customText.getText().toString();
mSharedData.setUniqueid(sCustomId);
mSharedData.commit();
break;
case R.id.cbRandom:
mSharedData.setUniqueid(sRandomId);
mSharedData.commit();
default:
break;
}
}
}
【问题讨论】:
-
set setOnCheckedChangeListener as a inner class -
@MD 我有四个复选框。因此,检查是否使用 switch case 或优化方式,而不是使用上面链接中给出的方法
-
我的问题是 Android 数据绑定覆盖了我的检查更改侦听器。所以我删除了
android:checked="@={}绑定。 2015 年可能不适用。
标签: android performance android-fragments android-xml android-checkbox