据说我有3个复选框,每个复选框都有一个对应的字符串值。我想要的是,当我选中复选框1和2时,它们的相应字符串或值将全部放在编辑文本上。
Example:
[✓] Checkbox 1 (Egg)
[✓] Checkbox 2 (Hotdog)
[ ] Checkbox 3 (Cheese)
当我选中方框1和2.它将转到edittext并查看为“Egg”\ n +“Hotdog”或类似内容。 输出:
EDITTEXT:
Egg
Hotdog
这可能吗?谢谢你的帮助!
答案 0 :(得分:2)
package com.example.checkboxes;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private CheckBox egg, hotdog, cheese;
private OnClickListener checkboxclicklistener;
private EditText display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
egg = (CheckBox) findViewById(R.id.a);
cheese = (CheckBox) findViewById(R.id.c);
hotdog = (CheckBox) findViewById(R.id.b);
display = (EditText) findViewById(R.id.display);
createListener(egg);
createListener(hotdog);
createListener(cheese);
}
public void createListener(CheckBox checkbox) {
checkbox.setOnClickListener( new OnClickListener() {
StringBuilder checkeditems = new StringBuilder();
@Override
public void onClick(View v) {
//is checkbox checked?
if (((CheckBox) v).isChecked()) {
String checkboxname = ((CheckBox) v).getText().toString();
Toast.makeText(getApplicationContext(), checkboxname, Toast.LENGTH_LONG).show();
if(checkboxname.equalsIgnoreCase("egg"))
{
display.setText(display.getText().toString()+"\nEgg");
}
else if(checkboxname.equalsIgnoreCase("hotdog"))
{
display.setText(display.getText().toString()+"\nHotdog");
}
else if(checkboxname.equalsIgnoreCase("cheese"))
{
display.setText(display.getText().toString()+"\nCheese");
}
}
else if (((CheckBox) v).isChecked()==false)
{
String checkboxname = ((CheckBox) v).getText().toString();
if(checkboxname.equalsIgnoreCase("egg"))
{
display.setText(display.getText().toString().replace("\nEgg", ""));
}
else if(checkboxname.equalsIgnoreCase("hotdog"))
{
display.setText(display.getText().toString().replace("\nHotdog", ""));
}
else if(checkboxname.equalsIgnoreCase("cheese"))
{
display.setText(display.getText().toString().replace("\nCheese", ""));
}
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 1 :(得分:1)
您可以像这样使用setOnClickListener
CheckBox chkEgg;
EditText yourEditText;
String yourText;
public void addListenerOnChkIos() {
chkEgg = (CheckBox) findViewById(R.id.checkbox1);
chkEgg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//is chkEgg checked?
if (((CheckBox) v).isChecked()) {
yourText = yourText + "Egg";
yourEditText.setText(yourText);
}
}
});
}
我只为一个人做过 希望这有帮助