Android - Create spinner programatically display issue - android

Basically, my program is prompting user to choose subjects from MainActivity's checkbox (maximum 5 from 10) and send its isChecked boolean value to NextActivity. With each true value receive, I need to create a spinner for user to choose grades between from A-F.
However, the issue is that the spinner in layout shows like that.
I created a class for creating spinner
public void createSpinner(String spinnerTitle, Spinner spinnerNumber){
ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add(spinnerTitle);
spinnerArray.add("A");
spinnerArray.add("B");
spinnerArray.add("C");
spinnerArray.add("D");
spinnerArray.add("F");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinnerNumber.setAdapter(spinnerArrayAdapter);
}
Then, to get value from previous activity and check whether its true, for creating a spinner.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grade);
LinearLayout layout = new LinearLayout(this);
Spinner spinner1 = new Spinner(this);
Spinner spinner2 = new Spinner(this);
.....
Spinner spinner10 = new Spinner(this);
Boolean check01 = getIntent().getExtras().getBoolean("C001");
Boolean check02 = getIntent().getExtras().getBoolean("C002");
.....
Boolean check10 = getIntent().getExtras().getBoolean("C010");
if (check01 == true) {
createSpinner("Subject C0001",spinner1);
layout.addView(spinner1);
}
if (check02 == true) {
createSpinner("Subject C0002",spinner2);
layout.addView(spinner2);
}
.....
if (check10 == true) {
createSpinner("Subject C0003",spinner3);
layout.addView(spinner3);
}
Please advice how to let the spinner to display vertically and placed in the centre.
An also, how can I detect which spinner is created, so that I can get the value user choose from the spinner.

To display it vertically you need to set LinearLayout's orientation to vertical. You can do it like this in code.
layout.setOrientation(LinearLayout.VERTICAL);
To make Spinner appear in center set layout's gravity to CENTER_HORIZONTAL.
LayoutParams layout_params = new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT, Gravity.CENTER_HORIZONTAL);
layout.setLayoutParams(params);

Related

Android: Showing a toast message when the checkbox is checked for the dynamically created checkboxes

When an ImageButton is clicked a checkBox is created dynamically in my app.
The problem I'm facing is with toast messages not showing or let's say the listener I am using for the checkboxes to show a toast message when the checkbox is checked is working only for the current/latest checkbox that has been created. Not for the checkboxes that had been created previously.
Problem,
I saw that the problem could be with the variable (toDoCheckBox) I am using to save the newly created checkbox instance and every time it's getting overriding dynamically as I create newer checkboxes. So for the previous checkboxes, there is no reference pointing to them in order for the listener to work. (the problem could be this or not, i don't know for sure) Even if this is the problem i don't know how to solve it
What i tried is that,
creating the instance of checkbox on both onCreate as well as the createCheckBox method so that I could assign the listener in both the places.
on the onCreate()
on the createCheckbox()
Only the latest created checkbox works and shows the toast messages
Can someone help me or guide me with the problem,
I want the toast message to show for every checkboxes
i posted only the code that could be of some use
private CheckBox toDoCheckBox;
private EditText defaultEditText;
private List<CheckBox> listCheckBoxes;
private int previousViewId = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.defaultEditText = findViewById(R.id.defaultEditText);
toDoCheckBox = new CheckBox(this);
this.listCheckBoxes = new ArrayList<>();
this.checkBoxListener = new View.OnClickListener(){
#Override
public void onClick(View view){
if(toDoCheckBox.isChecked()){
toDoCheckBox.setChecked(true);
Toast.makeText(MainActivity.this,"You did a good work, keep it up!",Toast.LENGTH_SHORT).show();
}
}
};
toDoCheckBox.setOnClickListener(checkBoxListener);
}
public void createCheckBox() {
//CREATING A CHECKBOX
toDoCheckBox = new CheckBox(this);
toDoCheckBox.setText(defaultEditText.getText().toString());
toDoCheckBox.setTextSize(20);
toDoCheckBox.setId(View.generateViewId());
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) defaultEditText.getLayoutParams();
ConstraintLayout.LayoutParams newParams = new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT
);
newParams.width = params.width;
newParams.height = params.height;
//Constraints
newParams.startToStart = params.startToStart;
newParams.endToEnd = params.endToEnd;
newParams.topToTop = params.topToTop;
newParams.topToBottom = params.topToBottom;
//Margins
newParams.leftMargin = params.leftMargin;
newParams.topMargin = params.topMargin;
newParams.bottomMargin = params.bottomMargin;
newParams.rightMargin = params.rightMargin;
constraintLayout.addView(toDoCheckBox, -1, newParams);
previousViewId = toDoCheckBox.getId();
defaultEditText.setVisibility(View.INVISIBLE);
createEditText();
toDoCheckBox.setOnClickListener(checkBoxListener);
this.listCheckBoxes.add(toDoCheckBox);
totalCheckBox++;
}
Try to use the local checkbox object instead of the global toDoCheckBox.

Save dynamically created tablelayout on screen rotation

I am working on an app that uses 5 tabs and each tab has a different fragment. In all of these fragments I have from 1 up to 10 dynamically created tablelayouts and each one of them can have as many rows as the user wants. Each row may have up to 16 columns of EditText, Spinner, Checkbox. My problem is that when I rotate my phone I lose all the data inside these tablelayouts. My ViewPagerAdapter that hosts these fragments extends FragmentStatePagerAdapter. I am not losing any data outside the tables. I understand that when I rotate the phone they are recreated but I want to keep my data. I do not want to create a database because when I finish adding data in my app I want to save everything to a .txt file. This is code for one of my tables
table18 = (TableLayout) view.findViewById(R.id.blg_parameter18_table);
TableRow.LayoutParams tlparams18 = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
//Create header
TableRow table18HeaderRow = new TableRow(view.getContext());
table18HeaderRow.setLayoutParams(tlparams18);
TextView table18HeaderColumn0 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn0, R.string.blg_parameter18_0, tlparams18);
TextView table18HeaderColumn1 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn1, R.string.blg_parameter18_1, tlparams18);
TextView table18HeaderColumn2 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn2, R.string.blg_parameter18_2, tlparams18);
TextView table18HeaderColumn3 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn3, R.string.blg_parameter18_3, tlparams18);
TextView table18HeaderColumn4 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn4, R.string.blg_parameter18_4, tlparams18);
TextView table18HeaderColumn5 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn5, R.string.blg_parameter18_5, tlparams18);
TextView table18HeaderColumn6 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn6, R.string.blg_parameter18_6, tlparams18);
TextView table18HeaderColumn7 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn7, R.string.blg_parameter18_7, tlparams18);
TextView table18HeaderColumn8 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn8, R.string.blg_parameter18_8, tlparams18);
TextView table18HeaderColumn9 = new TextView(view.getContext());
setTableHeaderView(table18HeaderRow, table18HeaderColumn9, R.string.blg_parameter18_9, tlparams18);
table18.addView(table18HeaderRow);
createRowTable18(table18, table18NumOfRows, tlparams18);
public void createRowTable18(TableLayout table18, int numOfRows, TableRow.LayoutParams tlparams18) {
TableRow table18Row = new TableRow(table18.getContext());
table18Row.setLayoutParams(tlparams18);
table18Row.setId(numOfRows);
CheckBox table18RowColumn1 = new CheckBox(getContext());
CheckBox table18RowColumn2 = new CheckBox(getContext());
CheckBox table18RowColumn3 = new CheckBox(getContext());
CheckBox table18RowColumn4 = new CheckBox(getContext());
CheckBox table18RowColumn5 = new CheckBox(getContext());
CheckBox table18RowColumn6 = new CheckBox(getContext());
EditText table18RowColumn7 = new EditText(getContext());
final TextView table18RowColumn8 = new TextView(getContext());
EditText table18RowColumn9 = new EditText(getContext());
Spinner spinner18 = new Spinner(getContext());
ArrayAdapter<CharSequence> adapter18 = ArrayAdapter.createFromResource(getContext(),
R.array.blg_parameter18_1_array, android.R.layout.simple_spinner_item);
adapter18.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner18.setAdapter(adapter18);
table18Row.addView(spinner18);
spinner18.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.blg_parameter_18_1_0))) {
table18RowColumn8.setText(null);
} else if (selection.equals(getString(R.string.blg_parameter_18_1_a))) {
table18RowColumn8.setText("kWh");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_b))) {
table18RowColumn8.setText("lt");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_c))) {
table18RowColumn8.setText("lt");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_d))) {
table18RowColumn8.setText("Nm^3");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_e))) {
table18RowColumn8.setText("Nm^3");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_f))) {
table18RowColumn8.setText("kg");
} else if (selection.equals(getString(R.string.blg_parameter_18_1_g))) {
table18RowColumn8.setText("kWh");
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
setTableRowCheckBox(table18Row, table18RowColumn1);
setTableRowCheckBox(table18Row, table18RowColumn2);
setTableRowCheckBox(table18Row, table18RowColumn3);
setTableRowCheckBox(table18Row, table18RowColumn4);
setTableRowCheckBox(table18Row, table18RowColumn5);
setTableRowCheckBox(table18Row, table18RowColumn6);
table18RowColumn7.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
setTableRowEditView(table18Row, table18RowColumn7, tlparams18);
setTableRowTextView(table18Row, table18RowColumn8, tlparams18);
table18RowColumn7.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_NORMAL);
setTableRowEditView(table18Row, table18RowColumn9, tlparams18);
table18.addView(table18Row);
}
public void addRow18() {
createRowTable18(table18, table18NumOfRows, tlparams);
table18NumOfRows++;
}
public void removeRow18() {
if (table18NumOfRows > 0) {
table18.removeViewAt(table18NumOfRows);
table18NumOfRows--;
} else {
Toast.makeText(getContext(), "Δεν υπάρχουν γραμμές στον πίνακα", Toast.LENGTH_SHORT).show();
}
}
When I complete inserting data they are too many to save and recall them one by one everytime i rotate the phone. Any ideas?
When your orientation changes, Android destroys your current activity and creates a new activity again, so you must manage your state.
You can use onSaveInstanceState to save the state and then get the same it in onCreate, for example:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("MyObject", myObject);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
final MyDataType myData = savedInstanceState.getString("MyObject"));
// fill your layout...
}
}
You can manage the state of your fragments too, please check here. Fragments can be "retain his instance" please read this or this.
Here another great post.
In some projects where I worked, when the application was not prepared for screen rotation, we had to disable this configuration.
I hope this will be useful for you.
Android will automatically save and restore your tables and the associated text views, but you need to do a couple of things.
Make sure each view you want to save has an id. Only views will an id will be saved. See generateViewId and setId.
Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.
Even with an id set, Android will not by default save the value of a TextView presumably because TextViews tend to be static. You can force a save/restore of a TextView by using freezesText.
android:freezesText
If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. By default this is disabled; it can be useful when the contents of a text view is not stored in a persistent place such as a content provider. For EditText it is always enabled, regardless of the value of the attribute.
There may be some odds and ends to tend to, but that should be the bulk of the changes needed.

Align layout to the bottom of the screen when using a scroll view and adding programmatically views

I have a form with a bunch of relative layouts, each one representing a group.
These are of two kind. One is the filter area which contains a spinner to choose a filter and an edit box for the input from the user and there can be multiple ones. The other kind has only one instance and contains a button that adds the aforementioned kind. This is aligned with the bottom of the parent which is a relative layout that contains all the others. This is also contained into a scroll view so it scrolls when the number of filter areas make the height bigger than the screen. My problem is that once I add enough filter areas to exceed the height of the screen the button gets moved once out of screen, then when you scroll down and press it again to add another one the button stays there. It's like the relative layout doesn't grow any more.
Is it something I have to set up in the xml?
The original xml is the following:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->
<RelativeLayout
android:id="#+id/searchLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_vertical_margin"
tools:context="com.kadis.materialref.Search">
<RelativeLayout
android:id="#+id/controlArea"
android:layout_width="match_parent"
android:layout_height="#dimen/controlAreaHeight"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/activity_vertical_margin">
<View
android:id="#+id/dividerControl2"
style="#style/Divider"/>
<Button
style="#style/AddButton"
android:id="#+id/addAttributeButton"
android:layout_centerHorizontal="true"
android:layout_width="#dimen/addButtonWidth"
android:layout_height="wrap_content"
android:layout_below="#+id/dividerControl2"
android:onClick="addFilter"
android:text="#string/addSearchAttributeString"/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/filterArea0"
android:layout_width="match_parent"
android:layout_height="#dimen/filterLayoutHeight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="#dimen/filterArea">
<Spinner
android:id="#+id/filterOperatorSelector0"
android:layout_width="#dimen/operatorSpinnerWidth"
android:layout_height="#dimen/filterSpinnerHeight"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Spinner
android:id="#+id/filterAttributeSelector0"
android:layout_width="wrap_content"
android:layout_height="#dimen/filterSpinnerHeight"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_toEndOf="#id/filterOperatorSelector0"
android:layout_toRightOf="#id/filterOperatorSelector0"/>
<EditText
android:id="#+id/filterInput0"
style="#style/SearchFormFieldText"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/filterAttributeSelector0"
android:text="Hello World"/>
</RelativeLayout>
</RelativeLayout>
This is the initial screen when first opening it.
The code for the screen is the following.
public class Search extends Activity
{
private String[] filterAttributes;
private String[] filterOperators;
private Spinner originalAttributeSelector;
private Spinner originalOperatorSelector;
private int lastAddedFilterAreaId;
// private MultiSelectionSpinner multiSpinner;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
lastAddedFilterAreaId = R.id.filterArea0;
// Get window sizes
DisplayMetrics dm = new DisplayMetrics();
getWindow().getWindowManager().getDefaultDisplay().getMetrics(dm);
int displayWidth = dm.widthPixels;
// Get items in spinners (attributes to search on an doperators to apply).
filterAttributes = getResources().getStringArray(R.array.attributes);
filterOperators = getResources().getStringArray(R.array.operators);
// multiSpinner = (MultiSelectionSpinner) findViewById(R.id.FilterSpinner);
// multiSpinner.setItems(filterAttributes);
originalOperatorSelector = (Spinner) findViewById(R.id.filterOperatorSelector0);
// Add items on the spinner.
ArrayAdapter<String> operatorSpinnerAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterOperators);
operatorSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
originalOperatorSelector.setAdapter(operatorSpinnerAdapter);
// Fix the width of the spinner so it doesn't get resized when making selections.
// Get the screen width and subtract the width of the button next to the spinner.
originalAttributeSelector = (Spinner) findViewById(R.id.filterAttributeSelector0);
originalAttributeSelector.getLayoutParams().width = displayWidth - originalOperatorSelector.getWidth();
// Create the adapter containing the list of choices for the spinner (as well the style for it)
// and bind it to the spinner.
ArrayAdapter<String> attributeSpinnerAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterAttributes);
attributeSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
originalAttributeSelector.setAdapter(attributeSpinnerAdapter);
originalAttributeSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
// Make the selected text of the spinner slide.
view.setSelected(true);
// Get container, the RelativeLayout.
RelativeLayout filterArea = (RelativeLayout) parent.getParent();
// Get input element, EditText.
View filterInput = filterArea.getChildAt(filterArea.getChildCount()-1);
// Disable the add button if the selected values is the first (Please make a selection)
if (id == 0)
{
((EditText) filterInput).setText("");
filterInput.setEnabled(false);
} else
{
findViewById(R.id.filterInput0).setEnabled(true);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void addFilter(View view)
{
// New Relative Layout to be added.
RelativeLayout filterLayout = createFieldArea();
// Add the operator spinner to the filter layout.
Spinner filterOperatorSelector = createFilterOperatorSelector();
filterLayout.addView(filterOperatorSelector);
// Add the attribute spinner to the filter layout, next to the operator spinner.
Spinner filterAttributeSelector = createFilterAttributeSelector(filterOperatorSelector);
filterLayout.addView(filterAttributeSelector);
// Add an Edit Text as the placeholder for the user input in the filter layout, below the attribute spinner.
EditText filterInput = createFilterInputField(filterAttributeSelector);
filterLayout.addView(filterInput);
// Adding the whole filter layout to the search layout (whole screen)
RelativeLayout searchLayout = (RelativeLayout) findViewById(R.id.searchLayout);
searchLayout.addView(filterLayout);
RelativeLayout controlArea = (RelativeLayout) findViewById(R.id.controlArea);
}
private RelativeLayout createFieldArea()
{
// Generate id for new relative layout to be created.
int filterLayoutId = MiscUtils.generateViewId();
RelativeLayout filterLayout = new RelativeLayout(this);
filterLayout.setId(filterLayoutId);
// Define width and height parameters.
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
getResources().getDimensionPixelSize(R.dimen.filterLayoutHeight));
// Define position
rlp.addRule(RelativeLayout.BELOW, lastAddedFilterAreaId);
rlp.addRule(RelativeLayout.ALIGN_PARENT_START);
rlp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
filterLayout.setLayoutParams(rlp);
// Update which is the latest added filter layout
lastAddedFilterAreaId = filterLayoutId;
return filterLayout;
}
private Spinner createFilterOperatorSelector()
{
Spinner filterOperatorSelector = new Spinner(this);
filterOperatorSelector.setId(MiscUtils.generateViewId());
// Add items on the spinner.
ArrayAdapter<String> spinnerArrayAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterOperators);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
filterOperatorSelector.setAdapter(spinnerArrayAdapter);
// Define width and height parameters.
RelativeLayout.LayoutParams rlpSp = new RelativeLayout.LayoutParams(
getResources().getDimensionPixelSize(R.dimen.operatorSpinnerWidth),
getResources().getDimensionPixelSize(R.dimen.filterSpinnerHeight));
// Define position
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_START);
// Set layout parameters
filterOperatorSelector.setLayoutParams(rlpSp);
return filterOperatorSelector;
}
private Spinner createFilterAttributeSelector(Spinner filterOperatorSelector)
{
Spinner filterAttributeSelector = new Spinner(this);
filterAttributeSelector.setId(MiscUtils.generateViewId());
// Add items on the spinner.
ArrayAdapter<String> spinnerArrayAdapter =
new ArrayAdapter<>(this, R.layout.spinner_item_material_ref, filterAttributes);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
filterAttributeSelector.setAdapter(spinnerArrayAdapter);
// Define width and height parameters.
RelativeLayout.LayoutParams rlpSp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
getResources().getDimensionPixelSize(R.dimen.filterSpinnerHeight));
// Define position
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_END);
rlpSp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rlpSp.addRule(RelativeLayout.END_OF, filterOperatorSelector.getId());
rlpSp.addRule(RelativeLayout.RIGHT_OF, filterOperatorSelector.getId());
// Set layout parameters
filterAttributeSelector.setLayoutParams(rlpSp);
return filterAttributeSelector;
}
private EditText createFilterInputField(Spinner filterAttributeSelector)
{
ViewGroup parent = (ViewGroup) filterAttributeSelector.getParent();
EditText filterInput =
(EditText) getLayoutInflater().inflate(R.layout.search_attribute_input, null);
filterInput.setId(MiscUtils.generateViewId());
// Define width and height parameters.
RelativeLayout.LayoutParams rlpET = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
// Define position
rlpET.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
rlpET.addRule(RelativeLayout.ALIGN_PARENT_END);
rlpET.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
rlpET.addRule(RelativeLayout.ALIGN_PARENT_START);
rlpET.addRule(RelativeLayout.BELOW, filterAttributeSelector.getId());
// Set layout parameters
filterInput.setLayoutParams(rlpET);
return filterInput;
}
}
When I add the first layout that fills the screen and after I scroll down to find the button.
If I press the add button here nothing changes. I know from the debugger that the new layout was created so I am guessing it's out of the screen.

Create view programmatically with style

i have a problem with my application. Basically what it does, is when i click a button, it creates 3 fields (2 editText and 1 spinner) on a scrollView. The thing works well, the only problem that im having, is related with the style, the activity bgColor is white(as the rest of the app) but, when i create elements programmatically, these elements doesnt have the look of the rest of my app. The editTexts are white with white letters (impossible to read since my bgColor is white as well) and its the same thing with the spinner. What can i do? Here is a snipet of code so you can see what im doing here.
public class AddIngredients extends Activity {
public int Count = 0;
public String[] spinnerArray = {"Gr", "kg", "Cups", "ml", "L", "oz"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addingredients);
final TableLayout lm = (TableLayout) findViewById(R.id.TableMain);
TableLayout.LayoutParams params = new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button addMore = (Button)findViewById(R.id.addmore);
addMore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TableRow ll = new TableRow(getApplicationContext());
//ll.setOrientation(LinearLayout.HORIZONTAL);
EditText product = new EditText(getApplicationContext());
product.setHint(" Ingredient "+Count +" ");
// Create Button
EditText amount = new EditText(getApplicationContext());
// Give button an ID
amount.setId(Count);
amount.setHint("Quantity");
final Button btn2 = new Button(getApplicationContext());
btn2.setId(Count);
btn2.setText("Remove " + Count);
Spinner spinner = new Spinner(getApplicationContext());
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
ll.addView(product);
ll.addView(amount);
ll.addView(spinner);
lm.addView(ll);
Count = Count + 1;
I know my XML is working well because if i create the 3 views on my xml, they look great. PD: Thx in advance for any help! Greetings.
you can use
amount.setTextColor(Color.BLACK);
to set colour of text to black or any other colour
same can be used for spinner
Here's how I set the colors of my edit text lines and other theme-related android views.
http://android-holo-colors.com/
I just picked the color and views I wanted, then unzipped them in my res folder, then set the theme according the android tutorials.
I recommend backing up your res folder first, in case you don't like the results.
Garret
I had a error in my code. When creating the fields, i was using
(getApplicationContext());. I fixed it using MyApplicationName.this.

Android, SpannableString, ArrayAdapter and Listview

i am newbie to android and i got a question for you. I want to add icon to a text in a listview. I'm adding the rows(textview) to listview dynamically with below code. But the text doesnt contain the icon.
.
.
.
btnicon = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
txt.setText(" denemedene",BufferType.SPANNABLE);
list = (ListView)findViewById(R.id.listview);
dizi = new ArrayAdapter<String>(this, R.layout.text);
list.setAdapter(dizi);
btnicon.setOnClickListener(click);
.
.
.
private OnClickListener click = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == btnicon){
SpannableString spans = new SpannableString(txt.getText());
Drawable dra = getResources().getDrawable(R.drawable.p1);
dra.setBounds(0, 0, dra.getIntrinsicWidth() , dra.getIntrinsicHeight());
ImageSpan span = new ImageSpan(dra,ImageSpan.ALIGN_BASELINE);
spans.setSpan(span, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
dizi.add(spans.toString());
}
}
};
it is something about the toString method. Because when i change the
dizi.add(spans.toString());
line with
txt.setText(spans,BufferType.SPANNABLE);
it works, i can see the icon on text. I have no idea why it is not working with toString() method.
Any ideas?
Thanks..
There is an example for custom list adapter in this post: https://stackoverflow.com/a/15272092/1752867
You can create your custom adapter like that and change checkbox component with imageView or ProgressBar in the layout

Categories

Resources