I was wondering if it was possible to ouput xml elements such as editText and textView based off user input. For example I'm making a simple game app and in the app you get taken to a new activity where it asks the amount of players. Based off the input (e.g. 5) I woulld like to display editText's and textViews so the players can be given names. Is this possible with Java and if so, how?
Sure is, though without having to go through XML.
Pass the number of players to the next activity as an argument. Then make sure you have a ViewGroup (LinearLayout for example) in the second activity's layout.
Then loop through and create the Views dynamically:
ViewGroup container = findViewById(R.id.linearLayout);
for( int i = 0; i < numberOfPlayers; i++ ){
EditText et = new EditText(this);
et.setHint(R.string.new_player_hint);// String providing a hint to the user
container.addView(et);
}
You can put the EditTexts in a List or if that's all you'll have you can directly cycle over the ViewGroup's children to get their values later on:
for( int i = 0; i < container.getChildCount(); i++ ){
String playerName = ((EditText) container.getChildAt(i)).getText().toString();
}
If you're going to have many possible players you should wrap the LinearLayout in a ScrollView.
Because you'll likely use this in onCreate remember that you can't rely on the EditText to save its own data in case the Activity is destroyed, so save them yourself and feed them back in when re-creating.
Related
I need to add 5 Input fields (EditText) dynamically one by one on button click and want to take values from them and store them into database using Room Persistence with MVVM.
Here I'm adding the view dynamically
private void addEditTextView() {
View inputView = getLayoutInflater().inflate(R.layout.row_edit_text, null, false);
EditText val1 = inputView.findViewById(R.id.input_value_1);
binding.layoutList.addView(inputView);
}
Any suggestion would be very helpful.
Thank you in advance.
Add view based on child count
private void addEditTextView() {
if (binding.layoutList.getChildCount() <= 5) {
View inputView = getLayoutInflater().inflate(R.layout.row_edit_text, null, false);
EditText val1 = inputView.findViewById(R.id.input_value_1);
binding.layoutList.addView(inputView);
}
}
"When I clicked Add button it is adding input field one by one, this code is working but I just want to limit for 5 fields not more not less and take values from them."
If you want to add exactly 5 fields on button click I recommend designing a fragment with the 5 fields in place, then when the button is clicked, inflate the fragment into your parent view. Then code the fragment appropriately with the data you're working with.
Then if you wanted, you could deflate the fragment on button click to clear the view or add some other way to clear the fragment when you want. Much easier than what you're doing currently in my own opinion.
You might as well include a submit button in your fragment assuming this is some kind of form.
You can simply define an integer and increase it every time you add the EditText but you should check if your integer is less than 5 everytime the method is called.
Example
private void addEditTextView() {
int count = 0;
if (count < 5){
View inputView = getLayoutInflater().inflate(R.layout.row_edit_text, null, false);
EditText val1 = inputView.findViewById(R.id.input_value_1);
binding.layoutList.addView(inputView);
count++;
}
}
I have a lot of textviews in my program .
I want the numbers inside these textviews to be separated by 3 to 3 .
Should I write code for any textview?
Is there a way to write code once and use it for the whole program?
Thank You .
I am not a Java developer, but I'm thinking you could write a class that inherits from the textview class and override the method that sets the text to separate the numbers. Then you'd just need to replace the class of your textview objects with your new class, which should be quite easy.
It dependes on the type of Layout. For example in a simple LinearLayout you can proceed like this :
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mylayout);
for(int k = 0 ; k < n ; k++){
TextView tView = new TextView(context);
tView.setText(k*3)
linearLayout.addView(tView);
}
Or another way could be iterating on all Views that are TextView setting the text. For example, assuming that mylayout is the parent view :
for(int k=0; k < mylayout.getChildCount(); k++ ){
if( mylayout.getChildAt(k) instanceof TextView ){
((TextView)mylayout.getChildAt(k)).setText(k*3);
}
}
In order to use your own TextView style, you can creat one by extend the TextView class and then use it in the xml activity
See example how to extend:
How to make a custom TextView?
In the constractor of your new TextView, you can add TextWacher by addTextChangedListener method to perform your number seperation.
See example how:
android on Text Change Listener
You have to use DecimalFormat and the grouping pattern
I am developing my first Android app. I have a table layout in my app, which will add rows dynamically. But, I want to convert the table rows into string. I tried "row.toString()" but I am not getting the expected result. Please find the following code snippet:
View view = null;
for(i = 0, j = tblayout.getChildCount(); i < j; i++)
{
view = tblayout.getChildAt(i);
TableRow rw = (TableRow)tblayout.getChildAt(i);
ColorDrawable viewColor = (ColorDrawable) view.getBackground();
int colorId = viewColor.getColor();
if(colorId == Color.parseColor("#E143ED23")) {
num ++;
//temCnt = view.toString();
temCnt = rw.toString();
}
}
Toast.makeText(getApplicationContext(),temCnt, Toast.LENGTH_LONG).show();
But it is not showing the actual table row data. It is showing some ids' or garbage value.
My requirement is:
I have 2 text boxes and 2 buttons. When the first button "Ok" is pressed the value inside the text boxes will be populated into the Table layout along with a checkbox. By default the row will be checked. But user can uncheck each items. After that, when the second button "Save All" is pressed, then it will search for all the table rows which are checked and it should insert the table rows into the my MS SQL table.
Is there any way for converting the table row into a string in Java? I really trapped on this. It would be very helpful if someone can help me on this.
Please help...
toString() is a very basic method in Java, C# and other programming languages. Java's Object class has a basic implementation for it and you can override this method in any class that inherits from Object (that is, every class whatsoever :)). I don't know if those that developed the TableRow class of Android have overridden this method. It could be that what you're getting is some unreadable, meaningless representation of a TableRow object.
Let's say you have a TextView called txtName within the TableRow, followed by a second TextView called txtNumber. You can get what you want by doing the following:
...
ColorDrawable viewColor = (ColorDrawable) view.getBackground();
int colorId = viewColor.getColor();
if(colorId == Color.parseColor("#E143ED23")) {
num ++;
//temCnt = view.toString();
TextView nameField = (TextView) rw.findViewById(R.id.txtName);
TextView numberField = (TextView) rw.findViewById(R.id.txtNumber);
temCnt = nameField.getText().toString() + ": " + numberField.getText().toString();
}
...
I am working on an android server-client application. There is a connection between the android application and the server.
Based on the first message from the server, a number of buttons is created and displayed on the screen. This number usually is between 1 and 10.
I don't want to initialise 10 buttons in my activity, as maybe, in the future, the number of buttons will increase to 20.
This is the way I initialise buttons and show them on the screen:
actionButtons = server.getActionButtons();
TableLayout buttonLayout =
(TableLayout) rootView.findViewById(R.id.tblLayoutButtons);
for(int i=0; i< actionButtons.length; i++)
{
btnAction.setWidth(100);
btnAction.setHeight(50);
btnAction.setTag(actionButtons[i]);
btnAction.setText(actionButtons[i].getName());
btnAction.setOnClickListener(btnActionClick);
buttonLayout.addView(btnAction);
}
This all works well. But my problem is that the server sends statusupdates for the buttons, every 3 seconds. Each button stands for a light, that can be on or off. A button that is 'ON' should have another background than a button that is 'OFF'. The buttons should be updated every time an update from the server is received.
How could this be done?
I would make it like this:
public void createButtons() {
actionButtons = server.getActionButtons();
TableLayout buttonLayout = (TableLayout) rootView.findViewById(R.id.tblLayoutButtons);
for(int i=0; i< actionButtons.length; i++)
{
btnAction.setWidth(100);
btnAction.setHeight(50);
btnAction.setTag(actionButtons[i]);
btnAction.setText(actionButtons[i].getName());
btnAction.setOnClickListener(btnActionClick);
btnAction.setId(i);
buttonLayout.addView(btnAction);
}
}
public void updateButton() {
//Get the ID of the button to toggle from the server and get the related view
ToggleButton buttonToToggle = (ToggleButton) findViewById(Integer.parseInt(server.getMessage()));
if (buttonToToggle.isChecked()) {
buttonToToggle.setChecked(false);
buttonToToggle.setBackground(R.drawable.offImage)
}
else {
buttonToToggle.setChecked(true);
buttonToToggle.setBackground(R.drawable.onImage)
}
}
This has the advantage, that you just have to send the ID of the Button and it gets toggled.
Alternatively you could send the binary value off all buttons, so you have to send also just a few bytes... In this case, you can assign the buttons their value in a for loop, almost like you create them.
Hope I helped ;)
If you want to change status of an already created Button then while creating them at run time assign them unique Id's using setID(int) method from the View class.
So for your button1 you can,
button1.setId(100);
and when you want to change thngs you can fetch the ID for the button and change it appropriately.
if(toChangeButton.getID() == 100){
//Change button1
}
Hope this helps.
Try to use the listview to add the buttons.When you get the data from the server,just update the adapter of the listview.
Hope this helps.
I started my own android app a few days ago since I needed a mobile application to store a bunch of data I collect in the hospital.
I'm pretty new to Java and android environment, although it seems easy to understand and very similar to C++.
Anyway, my application has a bunch of "EditText" and radio buttons and my question is:
How can I iterate through all those widgets (EditTexts and radio buttons)?
In .NET you could do a "for each element in container " loop but I can't seem to find a way to do this in Java/android environment.
Note: I don't know how many "widgets" exist in the activity, since some are created dinamicaly, others are hardcoded and some others show if some user preferences are set
Any help or hint would be appreciated.
for (int i = 0; i < rootView.getChildCount(); i++)
rootView.getChildAt(i)
Note that this will return View-s, you will have to check at runtime exactly what type of View you are currently looking at
It works.
Regarding the View type (ie Spinner, radioButton, EditText, etc) we can tag each type we want to parse in the Layout XML file and then add a conditional, ie:
if (Widget_Tag != null){
View Current_Widget = (View) rootView.getChildAt(i);
String Widget_Tag = (String) Current_Widget.getTag();
if (Widget_Tag.equals("MyEdiText")) {
//do something
}
}
the if (Widget_Tag != null){ is to prevent NullPointReferences. You can also doi it with a Try / Catch.
You can try this code:
LayoutInflater inflater = getLayoutInflater();
LinearLayout l = (LinearLayout) inflater.inflate(R.layout.main, null);
ViewGroup Current_Widget = (ViewGroup)l.getRootView();
for (int i = 0; i < Current_Widget.getChildCount(); i++)
Current_Widget.getChildAt(i);