Get information checkbox and EditText within a LinearLayout - android

I have a checkbox and EditText that generated dynamically by a query
This is the method that generates the checkbox and EditText and adds it to LinearLayout
private void create_form() {
JSONObject json = null;
int count = 0;
lm = (LinearLayout) findViewById(R.id.linearMain);
int seccion = Integer.parseInt(conf.get_id_seccion());
int tipo_solicitud = Integer.parseInt(conf.get_tipo_solicitud());
JSONObject jobj = obj_sqlite.get_form(seccion, tipo_solicitud);
try {
count = Integer.parseInt(jobj.getString("cont"));
json = new JSONObject(jobj.getString("json"));
} catch (Exception e) {
Log.e("getParams", e.getMessage());
}
for (int x = 1; x <= count; x++) {
try {
JSONObject json_row = new JSONObject(json.getString("row" + x));
CheckBox chb = new CheckBox(this);
chb.setText(json_row.getString("pregunta"));
chb.setId(json_row.getInt("pregunta_verificacion_supervision"));
chb.setTextSize(10);
chb.setPadding(8, 3, 8, 3);
chb.setTypeface(Typeface.SERIF, Typeface.BOLD_ITALIC);
chb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
lm.addView(chb);
EditText et = new EditText(this);
et.setHint("observaciones");
et.setId(json_row.getInt("pregunta_verificacion_supervision"));
et.setTextSize(10);
et.setPadding(8, 3, 8, 3);
et.setTypeface(Typeface.SERIF, Typeface.BOLD_ITALIC);
et.setInputType(android.text.InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE);
et.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
lm.addView(et);
} catch (Exception e) {
Log.e("getParams", e.getMessage());
}
}
}
Now I need to get all this checkbox selected along with your EditText to keep them in the table
this is my xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.php_mysql_sqlite.Formulario_verificacion_supervision" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title_activity_preguntas_revision" android:id="#+id/textView1"/>
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="285dp"
android:layout_height="330dp"
android:layout_marginTop="30dp" >
<LinearLayout
android:id="#+id/linearMain"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:background="#color/White"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/bt_regresar"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/scrollView1"
android:onClick="regresar"
android:text="#string/bt_regresar" />
<Button
android:id="#+id/bt_guardar"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/bt_finalizar"
android:layout_alignBottom="#+id/bt_finalizar"
android:layout_alignLeft="#+id/scrollView1"
android:text="#string/bt_guardar"
android:onClick="guardar" />
<Button
android:id="#+id/bt_finalizar"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/bt_regresar"
android:layout_alignBottom="#+id/bt_regresar"
android:layout_marginLeft="31dp"
android:layout_toRightOf="#+id/bt_guardar"
android:text="#string/bt_finalizar"
android:onClick="finalizar" />
and this is one image as is currently
http://i61.tinypic.com/2uo2hi8.jpg
by a method that is called on a button click, making the action to get the data
Thanks to all
PS: If you give me negative points, leave a comment of that because it has happened to me in the past and can not do wrong

You have two options.
Set a unique id to each checkbox and EditText and keep their ids in an ArrayList. When you want to do the check
for(int i = 0 ; i < listOfCboxIds.size() ; ++i) {
CheckBox cbox = (CheckBox) findViewById(listOfCboxIds.get(i));
if(cbox.isChecked()) {
// Do something
}
}
Keep the references to CheckBoxes and EditTexts in an ArrayList and just iterate over it. This is less CPU intensive.
List<CheckBox> yourCheckBoxes = new ArrayList<CheckBox>();
List<EditText> yourEditTexts = new ArrayList<EditText>();
try {
JSONObject json_row = new JSONObject(json.getString("row" + x));
CheckBox chb = new CheckBox(this);
chb.setText(json_row.getString("pregunta"));
chb.setId(json_row.getInt("pregunta_verificacion_supervision"));
chb.setTextSize(10);
chb.setPadding(8, 3, 8, 3);
chb.setTypeface(Typeface.SERIF, Typeface.BOLD_ITALIC);
chb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
lm.addView(chb);
EditText et = new EditText(this);
et.setHint("observaciones");
et.setId(json_row.getInt("pregunta_verificacion_supervision"));
et.setTextSize(10);
et.setPadding(8, 3, 8, 3);
et.setTypeface(Typeface.SERIF, Typeface.BOLD_ITALIC);
et.setInputTyp
e(android.text.InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE);
et.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
lm.addView(et);
yourCheckBoxes.add(chb);
yourEditTexts.add(et);
} catch (Exception e) {
Log.e("getParams", e.getMessage());
}
Once you need them
for(int i = 0 ; i < yourCheckBoxes.size() ; ++i) {
CheckBox cbox = (CheckBox) yourCheckBoxes.get(i);
EditText et = (EditText) yourEditTexts.get(i);
if(cbox.isChecked()) {
// Do something
}
}

Like Bojan Kseneman said the best option is to store your Views in a Data Structure. This could look like the following:
List<CheckBox> checkBoxes = new ArrayList<>();
List<EditText> editTexts = new ArrayList<>();
Then you add each box and editText to these Lists and later on you iterate over them like this:
for(int i = 0; i < checkBoxes.size(); i++){
CheckBox box = checkBoxes.get(i);
EditText editText = editTexts.get(i);
doSomeThingWithThem();
}
Hope this helps.

Related

setOrientation is not working for LinearLayout programatically

I am add dynamic data to the LinearLayout. default I declared as vertical orientation in xml. But I need to load horizontal data by programmatic way, Here set Orientation is not working.
LinearLayout llQuestionLayout = (LinearLayout) findViewById(R.id.ll_question_layout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
llQuestionLayout.setLayoutParams(layoutParams);
llQuestionLayout.setOrientation(LinearLayout.HORIZONTAL);
private void populateLikert() {
if(llQuestionLayout.getChildCount() > 0) {
llQuestionLayout.removeAllViews();
}
RadioGroup radioGroup = new RadioGroup(this);
for(int i =0; i < 5; i++) {
RadioButton radioButton = (RadioButton) LayoutInflater.from(this).inflate(R.layout.likert_radio_button, null, false);
radioButton.setText("" + (i + 1));
radioGroup.addView(radioButton);
}
llQuestionLayout.addView(radioGroup);
}
<LinearLayout
android:id="#+id/ll_question_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:orientation="vertical"/>
Please suggest correct answer.

Create buttons programmatically goes new line

I created a layout which programmatically created buttons (see code). With this layout I have a column of buttons, but I would create something like the picture below. I tried something with linear layout but the buttons didn't go to new line automatically and didn't show, so I change it to table layout. How can I create something like the picture programmatically?
Thank you.
protected TableLayout layout;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout = (TableLayout) findViewById(R.id.workflows_activity_layout);
private void createButton() {
loading.setVisibility(View.VISIBLE);
layout.removeAllViews();
if (items.length == 0) {
TableRow row = new TableRow(this);
TextView no_item = new TextView(this);
no_questions.setText("there are no items");
no_questions.setTextSize(35);
row.addView(no_item);
layout.addView(row);
} else {
for (int i = 0; i < items.length; i++) {
TableRow row = new TableRow(this);
final Button btn = new Button(this);
TextView tw = new TextView(this);
tw.setText(items[i].getName());
tw.setTextSize(25);
btn.setBackgroundResource(R.drawable.button_image);
btn.setId(i);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int btn_selected = btn.getId();
Intent openItempage = new Intent(MainActivity.this, ItemsActivity.class);
startActivity(openItempage);
}
});
row.addView(btn);
row.addView(tw);
layout.addView(row, params);
items_buttons.add(btn);
items_nameText.add(tw);
}
}
loading.setVisibility(View.GONE);
}
There's an easy way to achieve what you want. Look at this code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical">
<TableLayout
android:id="#+id/tab_lay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:stretchColumns="*"
android:gravity="center_vertical" />
TabLayout tab_lay = (TableLayout)view.findViewById(R.id.tab_lay);
for(int i = 1; i <= 4; ){
TableRow a = new TableRow(getActivity());
TableRow.LayoutParams param = new TableRow.LayoutParams(
TableRow.LayoutParams.FILL_PARENT,
TableRow.LayoutParams.WRAP_CONTENT, 1.0f);
a.setLayoutParams(param);
a.setGravity(Gravity.CENTER_VERTICAL);
for(int y = 0; (y < 2) && (i <= 4); y++) {
Button x = new Button(getActivity());
x.setText("Text " + i);
x.setGravity(Gravity.CENTER);
TableRow.LayoutParams par = new TableRow.LayoutParams(y);
x.setLayoutParams(par);
int ids = i;
x.setId(ids);
x.setOnClickListener(this);
a.addView(x);
i++;
}
tab_lay.addView(a);
}
If you want more buttons, then just change 4 which is compare to i to your value. Hope I help.
You can implement this using labraries, for instance
FlowLayout
Usage:
<com.wefika.flowlayout.FlowLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="start|top">
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Lorem ipsum" />
</com.wefika.flowlayout.FlowLayout>
Another solution is:
AndroidFlowLayout
Usage:
<com.liangfeizc.flowlayout.FlowLayout
android:id="#+id/flow_layout"
flowlayout:vertical_spacing="10dp"
flowlayout:horizontal_spacing="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

Creating an XML for Dynamically created Elements

I want XML for the TextViews and EditTexts created dynamically. Some blogs suggest that there are some Third Party Libraries that can do that but I wasn't able to find one. I am basically creating TextViews & EditTexts dynamically in my code on a button click.
Code:
LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
for (int x = 0; x < 1; x++) {
Display display = ((WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
int width = display.getWidth() / 3;
TextView et1 = new TextView(this);
et1.setBackgroundColor(color.transparent);
et1.setText("Untitled");
et1.setGravity(Gravity.LEFT);
EditText et = new EditText(this);
et.setHint("Click to add");
et.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
LayoutParams lp1 = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
LayoutParams lp2 = new LayoutParams(width,
LayoutParams.WRAP_CONTENT);
// lp1.addRule(RelativeLayout.BELOW, et1.getId());
linearLayout1.addView(et1, lp2);
linearLayout1.addView(et, lp2);
XML:
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/addImage" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/addEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/scrollView1"
android:text="Edit" />
The question is, how do I achieve the XML for the TextView & EditText as a String value? Do I give them tags and ids statically in the code or is there any other way?
public static final void writeMapXml(Map val, String name, XmlSerializer out)
throws XmlPullParserException, java.io.IOException
{
if (val == null) {
out.startTag(null, "TextView");
out.endTag(null, "TextView");
return;
}
Set s = val.entrySet();
Iterator i = s.iterator();
out.startTag(null, "TextView");
if (name != null) {
out.attribute(null, "name", "TextView");
}
out.endTag(null, "TextView");
}
XMLSerializer provided by android itself is enough to make dynamic XMLs.

Android array result shows in multiple textview

I'm trying to show the result which I got from my array function which has multiple result into the textview
for example, if the result is 1, 3, 5, 7, 9, each result will be shown in each textview. There will be 10 textviews and only 5 textviews will be used in this case.
is anyone know how to do it?
//this function is used to determine how many page can be flipped. I used viewFlipper in this case. rangeValue is depending on the user input
public int binaryRangePage(int rangeValue){
int flipperPage = 1;
while(rangeValue >= 2){
rangeValue = rangeValue/2;
flipperPage++;
}
return flipperPage;
}
totalPage = binaryRangePage(rangeMode);
//initialization range for 2 dimensional table
binaryTable = new int[rangeMode+1][totalPage+1];
int n;
int i;
int k;
//looping the range
for(i=1; i<=rangeMode; i++){
n = i;
flipperPage = 1;
//looping for each page in viewFlipper
while(n>0){
remainder = n%2;
binaryTable[i][flipperPage] = remainder;
n = (int) Math.floor(n/2);
System.out.println("remainder["+i+"]["+flipperPage+"]: "+remainder);
flipperPage++;
}
//if the current page is less than total page which should has value, the remainder page will be filled with 0
if(flipperPage<=totalPage){
//looping untuk remainder page dgn 0
for(k=flipperPage; k<=totalPage;k++){
binaryTable[i][flipperPage] = 0;
System.out.println("remainder["+i+"]["+flipperPage+"]: 0");
flipperPage++;
}
}
I'm trying to shows the value of range which has remainder 1. for example, the range is 10, there will be 4 page which can be flipped. in the page 1, the value is 1, 3, 5, 7, and 9. these value will be showed in the textview
Sample code In xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
<TextView
android:id="#+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/hello_world" />
</LinearLayout>
And in java code :
private static String[] array = {"a", "b", "c"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView text = (TextView) findViewById(R.id.textview);
TextView text1 = (TextView) findViewById(R.id.textview1);
TextView text2 = (TextView) findViewById(R.id.textview2);
text.setText(array[0]);
text1.setText(array[1]);
text2.setText(array[2]);
}
It's just sample change your array and textviews.
You need to create your TextViews dynamically. This is the optimum way.
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
for (int i = 0; i <= array.length ; i++){
TextView tv = new TextView(getApplicationContext());
tv.setText(array[i]);
layout.addView(tv);
}
But since you tell that your TextViews are fixed, you need to do something which is not really "appropriate" for programming but here you go:
if (array[0]!=null){
textView1.setText(array[0]);
}
else{
textView1.setVisibility(View.GONE);
}
if (array[1]!=null){
textView2.setText(array[1]);
}
else{
textView2.setVisibility(View.GONE);
}
.
.
.
if (array[9]!=null){
textView10.setText(array[9]);
}
else{
textView10.setVisibility(View.GONE);
}

set two radio buttons in one row then next two radio is on second row and so on

i want to set 2 two radiobuttons one row , then next 2 radiobuttons on second row dynamically(Programmatically) I am new to android any body have idea or sample code of it. What i have do is:
RadioGroup radiogroup = (RadioGroup)findViewById(R.id.RadioGroup01);
for(int i=0;i<10;i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId(i);
rdbtn.setText("test");
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.addView(rdbtn);
radiogroup.addView(rdbtn);
ll.addView(radiogroup);
//i%2 == 0
}
You can use below code:
Activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int row=0; row < 5; row++)
{
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
for(int i = 0; i < 2; i++) {
RadioButton rdbtn = new RadioButton(this);
rdbtn.setId((row * 2) + i);
rdbtn.setText("test " + rdbtn.getId());
ll.addView(rdbtn);
}
((ViewGroup)findViewById(R.id.radiogroup)).addView(ll);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<RadioGroup
android:id="#+id/radiogroup"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
</RelativeLayout>
Output on screen:
Hope this is what you were looking for. Cheers!

Categories

Resources