Beginner here so sorry for the lack of skill.
I'm trying to make an app that dynamically add edittext's and multiply them(rows) and then add the totals in a grand total.
I managed to make it dynamically add edittexits,make it scroll,reset but i'm trying to figure out how to assign id's to every textedit and then multiply the values(from the two edit texts on the rows) and then sum all the results in a grand total.I think i know how to set id's for every edittext( with setid(i) with a for) but i can't find a way to
I think i found a way but it's a bit hard to try just to possibly fail so i'm asking you guys for help.
There has to be an easier way that i don't know,since i'm an absolute beginner.
Please give me some alternatives if available and examples of how i can apply them.
Thanks in advance !
Here's my code so far :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void produsnou(View v) {
LinearLayout l1 = (LinearLayout) findViewById(R.id.layout1);
EditText et = new EditText(this);
et.setHint("Produs");
l1.addView(et);
int count = 4;
int i = 4;
for (i = 4; i < count; i++)
;
LinearLayout l2 = (LinearLayout) findViewById(R.id.layout2);
EditText et2 = new EditText(this);
et2.setHint("Cantitate");
et2.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l2.addView(et2);
et2.setId(i);
LinearLayout l3 = (LinearLayout) findViewById(R.id.layout3);
EditText et3 = new EditText(this);
et3.setHint("Pret");
et3.setInputType(InputType.TYPE_CLASS_NUMBER
| InputType.TYPE_NUMBER_FLAG_DECIMAL);
l3.addView(et3);
et3.setId(i + 1);
count = count++;
RelativeLayout l4 = (RelativeLayout) findViewById(R.id.layout4);
}
public void reload(View v) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
#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;
}
}
Create a List and push each EditText you have created into the List.
Once the list is completed, just go all over it and make the calculations.
Here's a sample code:
List<EditText> someList = new ArrayList<EditText>();
//Let's say we'd like to add 10 EditTexts
for(int i = 0; i < 10; i++){
EditText t1 = new EditText(); //The EditText you'd like to add to the list
t1.setText("lol"); //Give the EditText the value 'lol'
someList.add(t1); //Add the EditText to the list
}
//Go over the list and get the values
for(EditText t : someList){
String val = t.getText().toString(); //Get the value for the temp EditText variable t
}
In theory it should work, yet I haven't checked it.
Related
I have a LinearLayout ("ll") that is already created in xml and the app dynamically creates another LinearLayout inside of it and creates an EditText and a Button inside of that view. The button makes the whole LinearLayout destroy itself along with the EditText and Button inside it (the whole system is a player name entering activity). Anyway, I am trying to find a way to get the text from all of the EditTexts. I have tried using a for loop on "ll" and using ll.getChildAt() but I can't seem to use .getChildAt() on whatever ll.getChildAt() generates because getChildAt() generates a "View" not a "LinearLayout." I basically just need a way to search two children in, rather than just one. Also, if there is just a better way I should be doing this, let me know. I'm open to suggestions.
Here's my code if it will help:
NewGameCreate.java
public class NewGameCreate extends Activity {
int numOfPlayers = 0;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_game_create);
}
public void newPlayer(View view) {
numOfPlayers++;
final LinearLayout ll = findViewById(R.id.playerView);
final LinearLayout llNew = new LinearLayout(getApplicationContext());
llNew.setOrientation(LinearLayout.HORIZONTAL);
llNew.setId(numOfPlayers);
ll.addView(llNew);
EditText newName = new EditText(this);
newName.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
newName.setHint("Enter Player Name");
newName.setId(numOfPlayers);
newName.setWidth(0);
llNew.addView(newName);
final Button delete = new Button(this);
delete.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));
delete.setText("Delete");
delete.setId(numOfPlayers);
delete.setWidth(0);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = delete.getId();
ll.removeViewInLayout(findViewById(id));
Drawable back = ll.getBackground();
ll.setBackgroundColor(00000000);
ll.setBackground(back);
ll.invalidate();
}
});
llNew.addView(delete);
}
public void startGame(View view){
LinearLayout ll = findViewById(R.id.playerView);
List text = new ArrayList();
for(int loop = 0; loop < ll.getChildCount(); loop++) {
//this is the code in question and where I want to get the text from
//all my EditTexts
LinearLayout inner = ll.getChildAt(loop);
}
}
}
I think I found the answer to it. You need to change a little bit of code in the startGame() method I m providing the code for startGame below.
public void startGame(View view) {
LinearLayout ll = findViewById(R.id.playerView);
List text = new ArrayList();
for (int loop = 0; loop < ll.getChildCount(); loop++) {
//this is the code in question and where I want to get the text from
//all my EditTexts
LinearLayout inner = (LinearLayout) ll.getChildAt(loop);
for (int j = 0; j < inner.getChildCount(); j++) {
if (inner.getChildAt(j) instanceof EditText) {
EditText textET = (EditText) inner.getChildAt(j);
Log.d("TAG",textET.getText().toString());
}
}
}
}
In the above code you were able to get the first child only but as you have added a linearLayout with orientation Horizontal in a parent LinearLayout with orientation Vertical, you have written code for the child of parent layout i.e playerView. I have modified the code to get the elements of the child Linear layout and Log prints all the text from the EditText.
Hope that helps!!
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.
I am new to android. I want to display the 5 numbers in the Button. And also needs to display the arithmetic buttons also like below
14 12 13 12 11 ( These number to be displayed in the button )
+ - * / ( These arithmetic button also displayed in button)
I want to display like above dynamically. And i am using this code, but it displaying like below.( not displaying +, - *, / )
/ 14
/ 12
/ 13
/ 12
/ 11
I want to display like mentioned initially and also i want listen the button clicked
Its displaying Normal buttons, how i can display as like Graphic buttons. ( so that it will give more attraction)
Please find the code below.
setContentView(R.layout.dynamically_create_view_element);
final LinearLayout lm = (LinearLayout) findViewById(R.id.linearMain);
// create the layout params that will be used to define how your
// button will be displayed
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int j=0;j<5;j++)
{
// Create LinearLayout
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
// Create TextView
final Button btn1 = new Button(this);
// Give button an ID
btn1.setId(1);
btn1.setText("+");
btn1.setId(2);
btn1.setText("-");
btn1.setId(3);
btn1.setText("*");
btn1.setId(4);
btn1.setText("/");
// Create Button
final Button btn = new Button(this);
// Give button an ID
btn.setId(j+1);
int random1 = (int )(Math.random() * 20 + 1);
btn.setText(""+numbers[j]+"");
// set the layoutParams on the button
btn.setLayoutParams(params);
final int index = j;
// Set click listener for button
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.i("TAG", "index :" + index);
Toast.makeText(getApplicationContext(),
"Clicked Button Index :" + index,
Toast.LENGTH_LONG).show();
}
});
//Create four
//Add button to LinearLayout
ll.addView(btn1);
ll.addView(btn);
//Add button to LinearLayout defined in XML
lm.addView(ll);
}
Ok there are multiple issues with your code:
First, you're getting the below result
/ 14
/ 12
/ 13
/ 12
/ 11
because inside your for-loop you're setting the text of btn1 to / after setting the text of the Button to + then to - and then to *.
Also because you're creating a LinearLayout for each Button you're getting the numbers below each other.
I've taken the liberty to re-write the code a bit into something a bit more generic:
public class MainActivity extends Activity {
private LinearLayout lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LinearLayout) findViewById(R.id.lm);
// Create a LinearLayout for each row inside the outer LinearLayout.
LinearLayout firstRow = new LinearLayout(this);
firstRow.setOrientation(LinearLayout.HORIZONTAL);
// Create a String array of items you want to add to the inner LinearLayout.
String[] itemsToAddToFirstRow = { "14", "12", "13", "12", "11" };
createButtonsDynamically(firstRow, itemsToAddToFirstRow);
String[] itemsToAddToSecondRow = { "+", "-", "*", "/" };
LinearLayout secondRow = new LinearLayout(this);
secondRow.setOrientation(LinearLayout.HORIZONTAL);
createButtonsDynamically(secondRow, itemsToAddToSecondRow);
}
private void createButtonsDynamically(LinearLayout layoutToAddButtonsTo, String[] itemsToAdd) {
for (int i = 0; i < itemsToAdd.length; i++) {
final Button buttonToAdd = new Button(this);
buttonToAdd.setText(itemsToAdd[i]);
buttonToAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "I was clicked: " + buttonToAdd.getText(), Toast.LENGTH_SHORT).show();
}
});
layoutToAddButtonsTo.addView(buttonToAdd);
}
// In the end add all buttons inside the inner LinearLayout to the outer LinearLayout.
lm.addView(layoutToAddButtonsTo);
}
}
Add your own code to add the ids to the Buttons.
The end-result will look like this:
As far as your #2. goes:
You could a background image to your Buttons by calling setBackground(Drawable drawable) for the buttons or you completely re-style the standard Button.
Have a go at this guide from the official guidelines.
Hope this helps :-)
I m very new to Android.
I want to create a dynamic OnClick button functionality.
OnClick of "+" above , it should create a other layer , like this below.
My confusion , my entire design UI is in layout.xml.
How we can we include another layer in our UI on OnClick of "+" button.
Any input would be helpful.
Thanks !!!
You could do this programatically. XML is for static layouts.
Excuse my pseudo Android:
private LinearLayout root;
public void onCreate(Bundle b){
LinearLayout root = new LinearLayout(this);
root.addChild(createGlucoseReadingView());
setContentView(root);
}
private View createGlucoseReadingView() {
LinearLayout glucoseRoot = new LinearLayout(this);
glucoseRoot.addChild(new TextView(this));
return glucoseRoot;
}
public void onPlusClick(View button){
root.addChild(createGlucoseReadingView());
}
Something along those lines, I've obviosuly left out formatting and adding the layout params to the views, but you get the idea.
In your XML have one Vertical Linear Layout to add and remove EditTexts at runtime, Here I have shown you code I have used in my demos. To handle and maintain the usage.
Onclick of your Add and Minus button click
public void onClick(View view) {
super.onClick(view);
switch (view.getId()) {
case R.id.btnadd:
createTextview(counter);
counter++;
if (counter > 3) {
btnAdd.setVisibility(View.GONE);
btnRemove.setVisibility(View.VISIBLE);
}
break;
case R.id.btnremove:
removeView(counter);
txtoption[counter - 1] = null;
counter--;
if (counter < 3) {
btnAdd.setVisibility(View.VISIBLE);
btnRemove.setVisibility(View.GONE);
}
break;
}
}
Functions to create and remove view
private void createTextview(int index) {
txtoption[index] = new EditText(this);
txtoption[index].setSingleLine(true);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
param.bottomMargin = 10;
txtoption[index].setLayoutParams(param);
txtoption[index].setBackgroundResource(R.drawable.textbox);
txtoption[index].setTypeface(ttfDroidSherif);
lnpolloptions.addView(txtoption[index]);
}
private void removeView(int index) {
lnpolloptions.removeView(txtoption[index - 1]);
}
Your vertical LinearLayout to contain all the edittext childs
LinearLayout lnpolloptions = (LinearLayout) findViewById(R.id.lnpolloptions);
Arrays of edittext to be created of removed at runtime
private EditText[] txtoption = new EditText[4];
Onclick of submit to get value from each textbox
int length = txtoption.length;
for (int i = 0; i < length; i++) {
if (txtoption[i] != null) {
Log.i("Value",""+txtoption[i].getText());
}
}
I have programatically defined a set of imagebuttons in a for loop. For each button, I defined its setOnClickListener function which will put some data in the intent and then switch activity. However, it seems like no matter which button I clicked on, the extra data retrieved is set the the last value int he for loop. See code here:
public void onCreate(Bundle savedInstanceState) {
<...>
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlayout);
for (int i=1; i<=maxMapLoc; i++ ) {
mapLocation = i;
ImageButton btnMapLoc = new ImageButton(FirstActivity.this);
RelativeLayout.LayoutParams vp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
btnMapLoc.setLayoutParams(vp);
btnMapLoc.setBackgroundColor(Color.TRANSPARENT);
btnMapLoc.requestLayout();
String imgName = "map_loc_" + mapLocation;
int id = getResources().getIdentifier(imgName,"drawable",getPackageName());
btnMapLoc.setImageResource(id);
int imgMapLoc = 2000 + mapLocation;
btnMapLoc.setId(imgMapLoc);
rl.addView(btnMapLoc, vp);
btnMapLoc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("MapLocation", mapLocation);
startActivity(intent);
}
});
Any idea what I did wrong?
Thanks.
You could add a tag to your button with the current mapLocation value.
btnMapLoc.setTag(i);
...
// In onClick
intent.putExtra("MapLocation", v.getTag());
...
The reason why you only get the last value of mapLocation is that the code inside your onClick() is run when the user pushes a button. In other words your are querying mapLocation long after the loop built your buttons. You need to create a reference to the current mapLocation in each loop iteration, like with the tag feature.