How to define ChekBoxes in Java?
I face a problem in defining the CheckBox
in 开发者_如何学GoJava because I dont want to define it in a XML layout file.
I get the count of a HashTable
. I want to display CheckBoxes according to the number of that HashTable count.
Here is the code
public class SHO extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
In this class I want to define the chekboxes without using the XML layout file.
How can I achieve that?
Did you try just adding them to your view and tinkering with it?
If we assume you have a LinearLayout as your root view, then you could do:
CheckBox mCheckbox = new CheckBox(this);
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear_id);
mLinearLayout.addView(mCheckbox);
That's the most simple way to add a checkbox dynamically. If you need more of 'em, just do it in a for loop that is controlled by the amount of hash tables?
Edit: Obviously, there's a lot of ways to add 'em and control your view through code, but these are just the very basics.
Pretty sure there's a lot of Google results if you try something like "android ui dynamically" or whatever.
import android.app.Activity; import android.os.Bundle; import android.widget.ScrollView; import android.widget.LinearLayout; import android.widget.Button; import android.widget.TextView; import android.widget.EditText; import android.widget.CheckBox;
public class dic_tut3 extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
TextView tv = new TextView(this);
tv.setText("Dynamic layouts ftw!");
ll.addView(tv);
EditText et = new EditText(this);
et.setText("weeeeeeeeeee~!");
ll.addView(et);
Button b = new Button(this);
b.setText("I don't do anything, but I was added dynamically. :)");
ll.addView(b);
for(int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(this);
cb.setText("I'm dynamic!");
ll.addView(cb);
}
this.setContentView(sv);
}
}
精彩评论