Thursday, 12 September 2013

Using radio buttons and check boxes for similar task (Android)

Using radio buttons and check boxes for similar task (Android)

I have a EditText view and a checkBox (hide), and two radioButtons (hide
and show). The function of the buttons and checkbox is to hide or show the
hinto the EditView. I guess the first question is why I'd want to do this
in the first place. Well, I'm totally new to android and I'm just trying
different things out.
When I run the code though, the Activity fails to launch. I tested the
program before I even placed any radio buttons, and it was working just
fine with only the check box in the program. So I'm assuming the problem
lies somewhere with the radio buttons, or a combination of both used for
the same task.
here's my code:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class EmPubLiteActivity extends Activity implements
CompoundButton.OnCheckedChangeListener {
CheckBox cb;
EditText et;
RadioButton rbHide;
RadioButton rbShow;
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cb = (CheckBox)findViewById(R.id.cbHideHint);
cb.setOnCheckedChangeListener(this);
et = (EditText)findViewById(R.id.editText1);
rbHide = (RadioButton)findViewById(R.id.rbHide);
rbShow = (RadioButton)findViewById(R.id.rbShow);
RadioGroup rg = new RadioGroup(this);
rg.addView(rbHide);
rg.addView(rbShow);
rbHide.setOnCheckedChangeListener(this);
rbShow.setOnCheckedChangeListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.em_pub_lite, menu);
return true;
}
@Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
switch (view.getId()) {
case R.id.cbHideHint:
if (isChecked) {
et.setHint(R.string.nothing);
rbHide.setChecked(true);
}
else {
et.setHint(R.string.text_here);
rbShow.setChecked(true);
}
break;
case R.id.rbHide:
et.setHint(R.string.nothing);
cb.setChecked(false);
break;
case R.id.rbShow:
et.setHint(R.string.text_here);
cb.setChecked(true);
}
}
}
I'm getting the following error, along with a bunch of others, but I have
a feeling this is where the problem is:
java.lang.IllegalStateException: the specified child already has a parent.
You must call removeView() on the child's parent first.
What does this error mean, and how can I fix it?

No comments:

Post a Comment