I am just starting writing Android apps. I have done some beginner's tutorials, but I'm having trouble with the next step for which I could not find any helpful answer.
I want to write an app that computes the value of a complex function which depends on a three parameters. This works if I put everything on a single view:
For each parameter one TextField (with the parameter name) plus one EditText field to enter the value. At the bottom there is one Button, and when this is clicked, the result is displayed in another TextField.
But now I want improve the layout (plus I want to learn how to deal with more complex structures):
Two of the parameters are usually just set once and then kept at their values. So I decided to move these two parameters to a different view.
No I'm looking for recommendations (and hopefully links example code):
Which structure should I use? It seems that I do not need to use different activities, but one activity with different views should do the job.
ViewSwitcher sounds reasonable, since I only require two different views in this case. On the other hand ViewFlipper may be preferable, since I can reuse this later for other projects with multiple views. I also read that ViewPager allows to swipe between different views.
How can I read an EditField if this is on a different view?
I tried to use ViewSwitcher, and it worked when I added an additional button to switch to a second view. But when I moved the TextField and EditField for parameters one and two
to the second view, the app does not run on the emulator, just stating "error in app" (while Eclipse shows no errors). From this, I guess that I have to do some additional work to pass data in EditText between different views.
I have not found any examples for this - can anybody give me some advice/examples?
Any help is appreciated
I figured that my initial description was maybe not too helpful without any code.
Here is my layout
<?xml version="1.0" encoding="utf-8"?>
<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/viewSwitcher1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView android:id="#+id/pg1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1st view" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:id="#+id/v1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="value1" />
<EditText android:id="#+id/val1"
android:text="2.0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView android:id="#+id/v2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="value2" />
<EditText android:id="#+id/val2"
android:text="3.0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:layout_width="wrap_content"
android:id="#+id/calc"
android:layout_height="wrap_content"
android:text="2*Val1 + Val2 =" />
<TextView android:id="#+id/res"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="24sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="switch view 1" />
</LinearLayout>
</LinearLayout>
<!-- next view -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView android:id="#+id/pg2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="View 2" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:id="#+id/b2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="switch view 2" />
</LinearLayout>
</LinearLayout>
</ViewSwitcher>
and here is my main activity:
package com.example.testas2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewSwitcher;
public class MainActivity extends Activity {
ViewSwitcher switcher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switcher = (ViewSwitcher)findViewById(R.id.viewSwitcher1);
initControls();
}
private void initControls()
{
Button calculate=(Button)findViewById(R.id.calc);
calculate.setOnClickListener(new Button.OnClickListener()
{public void onClick (View v) { calculate(); }});
Button b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new Button.OnClickListener()
{public void onClick (View v) { switcher.showNext(); }});
Button b2=(Button)findViewById(R.id.b2);
b2.setOnClickListener(new Button.OnClickListener()
{public void onClick (View v) { switcher.showPrevious(); }});
calculate();
}
private void calculate()
{
EditText val1=(EditText)findViewById(R.id.val1);
EditText val2=(EditText)findViewById(R.id.val2);
TextView res=(TextView)findViewById(R.id.res);
Double Val1=Double.parseDouble(val1.getText().toString());
Double Val2=Double.parseDouble(val2.getText().toString());
Double result = 2*Val1+Val2;
res.setText( String.format( "%.3f", result ) );
}
#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;
}
}
This version is working:
- when pushing the first button, it computes: result = 2 * value1 + value2)
- when pushing the button "switch view 1", it goes to the second view
- on the second view, when pushing the button "switch view 2", it goes back to view 1
But I can't get the following two pieces to work:
1) I would like to move the "switch view 1" button to the top of the first view, but this gives an error in the emulator ("Unfortunately testas2 has stopped").
2) I would like to move the input of the second value to the second view, but this gives the same error in the emulator.
What am I doing wrong?
Why does the order of the elements in the layout matter, and how can I modify my code to make it work?
Example code -
TextView tField= (add cast here)findViewById(R.id.editText)
tfield.getText();
The above answer can be improved if you post some code of yours because findViewById at times depends on the container view and the above code will not work then as it will look for the textfield in the default view.
I just did "Project > Clean", restarted the app in the emulator, and now it works!
In other words, the solution for the original question is trivial (in fact there was no real problem). One can simply move elements in the layout file (TextView, EditText, Button) within a view or between views. The posted activity works always and the data (from the different TextView and EditView fields) is accessible everywhere in the code. Therefore, no explicit "transfer" of data between views is required.
Only after moving elements in the layout file one should do "Project > Clean".
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
For more info follow this link
Related
i want to learn how to create an android app, and i'm confused at :
1.first time launching my app will display viewpagers img_btn ice, img_btn jelly. and when img_buttons clicked will display which image chosen in profil.xml, is there any solution do it in 1 xml or i must create 2 xml for each button?
2.if user have choosed img_button, main_activity will change to profil.xml, so for the second time launch will show profil.xml. how can i do that?
main_activity.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:background="#000000"
>
<TextView
android:text="Choose char"
android:textSize="25dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#1e00ff"/>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_ViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"/>
page1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Halaman 2"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:textSize="54dp"
android:textColor="#0aedff"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:background="#00000000"
android:src="#drawable/btn_info"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="center_vertical|center"/>
page1.java
import android.support.v4.app.*;
import android.view.*;
import android.os.*;
public class page1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v=inflater.inflate(R.layout.halaman_1, container,false);
return v;
}
}
page2.xml and page2.java same as page1
English isn’t my first language, so please excuse any mistakes.
I am not sure what Fragment you extended. import android.support.v4.app.Fragment; or import android.app.Fragment; The below example assume you use support.v4
public void replaceFragment(Fragment fragment, String title) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(title)
.commit();
}
public void addFragment(Fragment fragment, String title) {
getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame, fragment, title)
.addToBackStack(title)
.commit();
}
you better has 2 xml (eg. page1.xml, page2.xml) and two classes extend Fragment, you may use the above function to first add a fragment, subsequently use replace when you open new fragments. Notice there is a R.id.content_frame in the functions given. That is from your main_activity.xlm, make a linear_layout name it content_frame, which will hold the open fragment. You then put a button on page1.xml, put an ImageView inside page2.xml, when the button on page1 has been clicked. use replaceFragment to open page2.xml
I have two layouts. I want to keep one layout gone when the activity is loaded and it should be visible onClick of another layout. so I have added this code OnClickListener of the layout.
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(linearLayoutFrom.getVisibility() == View.GONE){
linearLayoutFrom.setVisibility(View.VISIBLE);
}else{
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
And have set visibility of the layout gone in xml file..
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/LinearLayoutAdditionalContactFrom">
<ImageView
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/imageView13"
android:layout_marginLeft="20dp"
android:background="#drawable/ic_person_black_48dp"
android:layout_marginTop="05dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_marginRight="10dp"
android:drawableRight="#drawable/ic_expand_more_black_24dp"
android:text="Additional contact (optional)"
android:cursorVisible="false"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="60dp"
android:layout_marginRight="50dp"
android:layout_gravity="center"
android:visibility="gone"
android:id="#+id/LinearLayoutFrom">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText2"
android:layout_weight="1"
android:hint="Name"
android:layout_gravity="center"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText3"
android:layout_weight="1"
android:hint="Phone"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="OR"
android:id="#+id/textView19"
android:layout_gravity="center" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/textView13"
android:layout_marginLeft="48dp"
android:hint="Input if you're not receiver" />
</LinearLayout>
Unable to understand whats going wrong.. The listener is not getting called at all.. Please help..
Your problem is that your EditText is capturing the click event when you click on it. If you click somewhere else in the LinearLayout it should work.
You can replace the EditText with a TextView if you don't need the user to edit the content.
Change
linearLayoutFrom.setVisibility(View.VISIBLE);
To
findViewById(R.id.YOURLAYOUTID).setVisibility(View.VISIBLE);
I think you can't access to local vars in sub methods
It Seems That Layout Visibility is Already set to GONE, so Onlick listener is not working on hidden View and it should not work too.
INVISBLE means you are trying to add a listener to a view which is not there. You can add the listener to a visible view only.
WORKAROUND
1) Try to make a dummy view which is visible but having the same color as background.
2) Try to set the listener for parent and check the position (whether the position does
belongs to INVISIBLE view).
Please try to set the onClickListener to the EditText and to the ImageView and no to the LinearLayout
The problem is that the Handler of the EditText is most important that the LinearLayout handler.
Almost you can try to make a break point to the OnClick and see what is happend
This is an example to explain you how to do that:
in MainActivity Class:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout linearLayoutFrom;
private LinearLayout additionalContactFrom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
additionalContactFrom = (LinearLayout) findViewById(R.id.LinearLayoutAdditionalContactFrom);
linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
linearLayoutFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"linearLayoutFrom clicked!!!", Toast.LENGTH_SHORT)
.show();
if (additionalContactFrom.getVisibility() == View.GONE) {
additionalContactFrom.setVisibility(View.VISIBLE);
} else {
additionalContactFrom.setVisibility(View.GONE);
}
}
});
additionalContactFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"additionalContactFrom clicked!!!", Toast.LENGTH_SHORT)
.show();
if (linearLayoutFrom.getVisibility() == View.GONE) {
linearLayoutFrom.setVisibility(View.VISIBLE);
} else {
linearLayoutFrom.setVisibility(View.GONE);
}
}
});
}
}
in xml file:
<FrameLayout 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:orientation="vertical" >
<LinearLayout
android:id="#+id/LinearLayoutAdditionalContactFrom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_blue_dark"
android:orientation="horizontal" >
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayoutFrom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="60dp"
android:layout_marginRight="50dp"
android:background="#android:color/holo_green_light"
android:orientation="vertical"
android:visibility="gone" >
</LinearLayout>
<TextView
android:id="#+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="48dp"
android:hint="Input if you're not receiver"
android:textAppearance="?android:attr/textAppearanceSmall" />
</FrameLayout>
This is very important that when you want add some view (for example
add a linearlayout to another linerlayout). you should use framelayout or
relativelayout(do not use linearlayout) for do that.
My understanding was that all standard Views with an ID should save their state automatically, and upon trying this on an example I found it to be quite confusing.
I had only 1 activity and the main layout as listed below.
When I change the text of the TextView by clicking on the button, and then rotate the screen, the TextView does actually save it's state, but upon rotating again, it resets to it's default state.
Same happens if I edit it while in landscape and rotate: after first rotate it still saves it's state, but after another rotate (unless I change the text again) it resets to default value.
I'm really confused now. Could someone please explain this behavior to me. I wasn't able to find any other question (or answer) that explains this specific behavior.
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"
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=".MainActivity">
<TextView
android:id="#+id/activity_main_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:text="test"
android:textSize="50sp"
/>
<EditText
android:id="#+id/activity_main_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:maxLength="30"
android:maxLines="1"
/>
<Button
android:id="#+id/activity_main_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Set text"
/>
</RelativeLayout>
MainActivity.java:
package com.example.viewstatetest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private EditText editText;
private View button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.activity_main_textView);
editText = (EditText) findViewById(R.id.activity_main_editText);
button = findViewById(R.id.activity_main_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(editText.getText());
}
});
}
}
If you look at the TextView sources (in particular TextView#onSaveInstanceState()), you will see that text is saved only in two cases:
When user explicitly asked to do that by setting freezeText flag to true via android:freezesText="true" or TextView#setFreezesText(true)
When text within TextView has selection.
In your case both of these cases are false, so your text gets reset to its default state during orientation change.
Simple change to your layout will solve the issue:
<TextView
android:id="#+id/activity_main_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:freezesText="true"
android:maxLines="2"
android:text="test"
android:textSize="50sp"
/>
I have an activity inside my android app that lists some information inside ListView , in the top left corner of each Item there is a more information icon, when user touches this icon application should change the content of this list item to some useful information , and also the icon should change to another icon , for example a close icon , again when user touchs close icon application should show list item contents.
For changing the Icon i used this code, but first time that i click icon nothing happens , second time it changes, and sometimes when i click one of the icons the icon of another list item changes.
ListActivity.java
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewCliced, int position, long id)
{
img = (ImageView)viewCliced.findViewById(R.id.img_icon);
img.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
img.setImageResource(R.drawable.setting);
}
});
}
});
this code changes the icon but user should touch icon twice and sometimes change another list item's icon :|
this is the XML of ListView Item
listitem.xml
<?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:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:background="#drawable/item_select"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="8" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="top|left"
android:orientation="vertical" >
<ImageView
android:id="#+id/img_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="#drawable/bookabout" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="7"
android:gravity="right|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/txt_subject"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:text="نام فصل"
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:orientation="vertical" >
<TextView
android:id="#+id/txt_explanation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="15dp"
android:text="توضیحات فصل درسی"
android:textColor="#000000" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
How i should develop this feature ?
toggling between two kind of contents for a ListView item when user touches an Icon inside the ListView Item
I read a lot of article about list views but i couldn't find a way to do that,
Thank you very much for answering
Best Regards
"For changing the Icon i used this code, but first time that i click icon nothing happens , second time it changes, and sometimes when i click one of the icons the icon of another list item changes."
because you declare the listener inside the list listener so for the first time you click the icon your listener set (because you click list item ) and for the second time the icon responses. pull out listener of img and put it in onCreate method. Inside your adapter modify the getView method like this:
#Override
public View getView(int position, View row, ViewGroup parent) {
final int listItemPosition = position;
ImageView img = (ImageView)row.findViewById(R.id.image1);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Change icon here
// If you'd like to delete item use the code below
// List.remove(listItemPosition);
// Adapter.this.notifyDataSetChanged();
}
});
}
I have a page that returns a list of items backs from a database. I want to add each item to my android fragment as a checkbox dynamically with an onClick, that can tell if an item is being checked or un-checked.
How can I add checkboxes dynamically with on-clicks and different titles for each?
Below is the xml I am inserting the checkboxes into:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#e5e5e5"
android:layout_height="match_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:orientation="vertical"
android:background="#drawable/bg_card">
<!-- Card Contents go here -->
<TextView
android:id="#+id/styleDescription"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="15sp"
android:padding="5dip"
></TextView>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New CheckBox"
android:id="#+id/checkBox" />
</LinearLayout >
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:orientation="horizontal"
android:background="#drawable/bg_card">
<!-- Card Contents go here -->
<Button
android:id="#+id/buttonAddList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create List"
style="?android:attr/borderlessButtonStyle"
android:textColor="#color/orange"
android:textStyle="bold"
/>
</LinearLayout >
</FrameLayout>
</LinearLayout>
</ScrollView>
I currently have one checkbox in the above code. I plan on removing this. That checkbox is just to show where I want my check boxes to show up.
What you need to do first is add an id to your LinearLayout (in that XML file), the one which is going to hold the CheckBoxes. Then, in the code you need to get that LinearLayout by its id and use addView() to add CheckBoxes that you create dynamically. I imagine in pseudocode it'd look like this:
for (int i = 0; i < numberOfCheckBoxes; i++) {
CheckBox checkBox = new CheckBox();
checkBox.setTitle("Your title");
checkBox.setOnClickListener(new OnClickListener() {
// Your code to be executed on click
});
linearLayout.addView(checkBox);
}
Does this help?
PS: It'd be nice if you kept your code clean - ADT (and I believe Eclipse too) gives you the Shift+Ctrl+F shortcut to indent your code automatically - use it as often as possible ;)
Since you are processing database items, I suggest using a CursorAdapter to do the heavy work for you. A CursorAdapter, like any of the Adapter classes can process the database items and custom-fit them into a layout of your choice, to use in a ListView.
You have to make adjustments to your code:
Create a layout file that contains whatever you want to put in the dynamic list. This is an example, say it's named list_contents.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:orientation="vertical"
android:background="#drawable/bg_card">
<!-- Card Contents go here -->
<TextView
android:id="#+id/styleDescription"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="15sp"
android:padding="5dip"
></TextView>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New CheckBox"
android:id="#+id/checkBox" />
</LinearLayout >
</FrameLayout>
Then, instead of returning a List from your AsyncTask, return the Cursor itself
from your database. This Cursor will be processed by CursorAdapter. I recommend this guide:
http://www.gustekdev.com/2013/05/custom-cursoradapter-and-why-not-use.html
Implement the CursorAdapter methods:
In your implementation of newView(), inflate list_contents.xml (Note that if you use ResourceCursorAdapter you wouldn't need to do this)
In your implementation of CursorAdapter.bindView() do this:
CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox);
checkbox.setText(cursor.getString(cursor.getColumnIndex(YOUR_DATABASE_COLUMN_NAME_FOR_CHECKBOX_VALUES)));
checkbox.setOnCheckedChangedListener(listenerInitializedSomewhereFromFragmentCode);
Change your ScrollView to a ListView (it can be inside any Layout), and give it an id, say R.id.listview.
Finally, in the part where you process the List from the database, where we now have a Cursor instead, just do this:
CustomCursorAdapter cca = new CustomCursorAdapter(getActivity(), resultFromDatabase, 0);
listView.setAdapter(cca);
Note: getActivity() is for when you are working inside a Fragment. It should be a context, so inside an Activity it can just be "this".
Note2: listView should have been initialized at this point via findViewById.
Note3: If listView already has an Adapter and Cursor set, you should consider calling listView.getAdapter().changeCursor() instead.
Simple Code In Kotlin
fun createCheckbox() {
var arr_cb = arrayOfNulls<CheckBox>(checkbox_size)
val layout = findViewById<View>(R.id.layout_checkbox) as ViewGroup
val ll = LinearLayout(this)
ll.orientation = LinearLayout.VERTICAL
for (i in 0 until arr_cb.size) {
arr_cb[i] = CheckBox(this)
arr_cb[i]?.text = health_status.get(i).toString()
arr_cb[i]?.setPadding(25, 0, 0, 0)
arr_cb[i]?.id = i
arr_cb[i]?.tag = health_status[i]
arr_cb[i]?.setTextColor(resources.getColor(R.color.title_color))
arr_cb[i]?.setOnCheckedChangeListener(
arr_cb[i]?.let {
handleCheck(it)
})
arr_cb[i]?.buttonTintList =
ColorStateList.valueOf(resources.getColor(R.color.theme_color))
ll.addView(arr_cb[i])
}
layout.addView(ll)
}
handleCheck method
private fun handleCheck(chk: CheckBox): CompoundButton.OnCheckedChangeListener? {
return object : CompoundButton.OnCheckedChangeListener {
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
if (!isChecked) {
//uncheck
} else {
//check
}
}
}
}
and you want to do something use direct checkboxList object like as
val layout = findViewById<View>(R.id.layout_checkbox) as ViewGroup
val ll = LinearLayout(this#MedicalHistoryActivity)
ll.orientation = LinearLayout.VERTICAL
for (i in 0 until health_status.size) {
arr_cb[i]?.isEnabled = true
// do something like change color or more
}
layout.addView(ll)
for enable checkbox or more.
Thank you