Dynamic layout for textview - android - android

I am getting number of string from server.
I want to show it on layout like below image
Everytime I'll be getting different type of string. so how to create dynamic layout for textview?

May be you are looking for a Flow Layout.
https://github.com/ApmeM/android-flowlayout

using this code, we can able to create linear layout dynamically with inside textview. if you want, just modify the code to as you like, above asked..
onCreate() Method :
private Button[] btnAdd ,btnQuestionPalete ; // GLobally
private LinearLayout layout_button ;
layout_button = (LinearLayout) findViewById(R.id.button_layout);
btnAdd = new Button[100] ;
LayoutParams param2 = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);
btnQuestionPalete = new Button[100];
for (int i = 0; i < noOfButton; i++) {
linearQuestionPalettesRow = new LinearLayout(getApplicationContext());
linearQuestionPalettesRow.setOrientation(LinearLayout.VERTICAL);
linearQuestionPalettesRow.setLayoutParams(param2);
linearQuestionPalettesRow.setPadding(10, 10, 10, 10);
textView[i] = new TextView(getApplicationContext());
textView[i].setId(i+1);
textView[i].setText("test");
textView[i].setTextColor(Color.BLACK);
textView[i].setGravity(Gravity.CENTER_HORIZONTAL);
linearQuestionPalettesRow.addView(textView[i]);
layout_button.addView(linearQuestionPalettesRow);
}
xml code :
<LinearLayout
android:id="#+id/button_layout"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:orientation="horizontal"
>
</LinearLayout>

Its easy just add the stings to the array/arraylist and make arrayadapter out of it .Then pass it listView or DridView

You can use Table Layout to achieve this dynamically.
but i think you want your layout in zigzag manner like:
------------------
------------------
------------------
------------------
so you can do it using ListView(efficient)
but if you don't want this pattern and you don't have rows more than 5-10 then you can go for TableLayout

Related

How can I change ImageButton size programmatically?

I'm generating ImageButtons programmatically and I'm not able to change the size of the items using XML. So, I would like to do it programmatically too.
How can I do that?
My code :
String[] separated = result.split("%");
ImageButton [] txt =new ImageButton[20];
for(int i=0;i<txt.length;i++)
{
String getname = separated[i];
txt[i]=new ImageButton(hphotos.this);
Picasso.with(getBaseContext()).load("http://www.mywebsite.com/" + getname).into(txt[i]);
txt[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
scroll.addView(txt[i]);
Have you tried
yourView.setLayoutParams(new LayoutParams(width,height));
?

Adding multiple views to a view [duplicate]

This question already has answers here:
Android - Dynamically Add Views into View
(5 answers)
Closed 10 years ago.
I want to add a view comprising of 4 buttons and a textview to a linear layout and set that newly made view to a viewflipper...Client's requirement is that i need to create the layout the programmatically and not using an xml file
See this is sample code, this might helpful for you. Instaed of LockView you can mention other views..
lockLayout = (LinearLayout) findViewById(R.id.quick_lock_layout);
private void renderLockLayout() {
lockLayout.removeAllViews();
lockLayout.invalidate();
lockLayout.setLayoutParams(new LinearLayout.LayoutParams(
lockLayoutWidth + 7, (height / 6)));
/*
* Toast.makeText(ApplicationContext.getContext(), "Num count is :" +
* _totalLocks, Toast.LENGTH_SHORT).show();
*/
Log.i(getClass().getSimpleName(), "Total :" + _totalLocks);
lockViewArray = new LockView[_totalLocks];
for (int index = 0; index < _totalLocks; index++) {
LockView lockview = (LockView) inflater.inflate(R.layout.lockview,
null);
lockview.setLayoutParams(new LayoutParams((width),
LayoutParams.WRAP_CONTENT));
lockLayout.addView(lockview);
lockViewArray[index] = lockview;
}
lockLayout.invalidate();
}
It's recommended to define UI in XMl. But for your client requirement you can do it dynamically. In android, UI in xml and at run time (.java file) are optional each other.
So use java methods to create LinearLayout and add newly created views to it. Finally you can add this LinearLayout to ViewFlipper.

Alignment issue while implementing TableRow

I need to accomodate three columns in a TableLayout.
The following code creates the table row headers & then populates the values in the columns. Table layout has been defined in the layout xml.
TableLayout tableLay = (TableLayout) findViewById(R.id.table);
// Table Headers
TextView firstNameHeader = new TextView(this);
firstNameHeader.setGravity(Gravity.CENTER);
TextView lastNameHeader = new TextView(this);
lastNameHeader.setGravity(Gravity.CENTER);
TextView ageHeader = new TextView(this);
ageHeader.setGravity(Gravity.CENTER);
// Adding the Table headers to Table Row
TableRow empHeaderTableRow = new TableRow(this);
empDetailsTableRow.addView(firstNameHeader);
empDetailsTableRow.addView(lastNameHeader);
empDetailsTableRow.addView(ageHeader);
// Adding the Table Row to Table Layout
tableLay.addView(empDetailsTableRow);
// Adding Column Data
for(int count = 0; count < empDetails.size ; count++){
TextView firstNameData = new TextView(this);
firstNameData.setGravity(Gravity.CENTER);
firstNameData.setText(...);
TextView lastNameData = new TextView(this);
lastNameData.setGravity(Gravity.CENTER);
lastNameData.setText(...);
TextView ageData = new TextView(this);
ageData.setText(...);
ageData.setGravity(Gravity.CENTER);
TableRow empDataTableRow = new TableRow(this);
empDataTableRow.addView(firstNameData);
empDataTableRow.addView(lastNameData);
empDataTableRow.addView(ageData);
}
// Adding the Table Row to Table Layout
tableLay.addView(empDataTableRow);
There is alignment issue with the above code.
When any of the data like first name , last name exceeds a certain length , the entire colum shifts out of the screen. In that case , only one column is visible on the screen while the rest of the columns goes beyond the screen.
I want to set fixed column width for the three columns , so that if any data wrt to a particular column exceeds length, it will get truncated or displayed on the second line & the other column positions (aligned) is not disturbed.
Do I need to truncate the text if it exceeds the column width or it can be done automatically with the help of any method already available in TextView.
Any hints/suggestions welcome.
You need to set width of textView to be fixed to resolve this issue. You can also use weight for this purpose.
Use android:shrinkColumns and android:stretchColumns xml-attributes.
You can use textview.setMaxLines(maxlines) and textview.setwidht() to fix this problem.

getting integer value entered from dynamically created edittext in a dialog in Android throws NumberFormatException

I'm new, so sorry if this turns out so simple that I should have solved myself. I've spent a couple days thinking about it. I've researched a ton and searched many other posts here, but no success.
I have a dialog with DatePicker, Buttons, EditText fields, and Spinners. I can populate everything i need from the stored items in my DB to the dialog. But when i try to get the numbers entered into some of the EditText fields, it throws NumberFormatException. I can hard code values into variables to store, and hide my attempt to get the value in a try and it will run fine. The values get stored and when I open the dialog again they populate into the right areas.
Here's partial code-
EditText et = new EditText(getContext());
for(int i=0; i<=etcount; i++){
placed = -1; //reset for next iteration
//try to get number from edittext
et.findViewById(i);
placed = Integer.parseInt(et.getText().toString());
awake++;
/*
try {
//et.findViewById(i);
placed = Integer.parseInt(findViewById(i).toString());
//placed = Integer.parseInt(et.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}*/
I commented out the try block cause I wanted to troubleshoot quickly.
etcount variable is initialized at onCreate with -1 value, before getting values from DB. If there are values stored in the DB it gets incremented by 1, then code is called to dynamically add an EditText and Spinner to the layout. Also the EditText id is set to the value of etcount. Here is that code-
//this will be ran when +placement button pressed, or if there are items in db stored
//adds 2 rows to dialog, one for textview to label items, one row for edittext with number
//and spinner with what item it is
private void createTableRow(int numPlaced, int itmPlaced){
etcount++; //used to count how many edittext fields there are so that they can be saved later
spincount++; //to count how many spinner there are
tl = (TableLayout)findViewById(R.id.tableLayoutVisit); //the tablelayout name
//need to create row for textview, then another row for edittext and spinner
tr1 = new TableRow(this.getContext()); //table row 1, for textview
tr1.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
TextView tv = new TextView(this.getContext());
tv.setText("Amount Placed");
tv.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr1.addView(tv); //add textview to tablerow1
tl.addView(tr1, new TableLayout.LayoutParams( //add row to tablelayout
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr2 = new TableRow(this.getContext()); //tablerow2: edittext and spinner
tr2.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
EditText et = new EditText(this.getContext());
et.setId(etcount);
et.setInputType(InputType.TYPE_CLASS_NUMBER);
if(numPlaced!=0){ //if being populated from previous visit
et.setText(Integer.toString(numPlaced));
//et.setText("" +numPlaced);
}
//need to have listener to read data
et.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
Spinner spin = new Spinner(this.getContext());
spin.setId(spincount);
spinArray = getContext().getResources().getStringArray(R.array.itemplaced);
ArrayAdapter adapter = new ArrayAdapter(getContext(),
android.R.layout.simple_spinner_item, spinArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
if(itmPlaced!=-1){
spin.setSelection(itmPlaced); //assign correct value
}
spin.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr2.addView(et);
tr2.addView(spin);
tl.addView(tr2, new TableLayout.LayoutParams( //add row to tablelayout
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
I pass it (0,-1) if it is a new item and not currently stored in DB. Also you probably noticed I forced it to accept TYPE_CLASS_NUMBER. But I don't think the issue is there. Again, if I hard code values it will save into the DB and the next time I open it it dynamically creates EditText/Spinner row in layout and populates the EditText with the value in the DB.
So... something is wrong with the first section I think, the et.findViewById(i); or placed = Integer.parseInt(et.getText().toString());. The value of "etcount" should be -1 if nothing was populated from DB, and 0 etc(etcount++) each time something is populated from DB.
Sorry if this is longwinded, wanted to be specific. Hope this is enough info! Any help would be great!!! Thanks in advance.
Try this:
EditText et = new EditText(this);
for (int i = 0; i <= etcount; i++) {
placed = -1;
et = (EditText) this.findViewById(i);
placed = Integer.parseInt(et.getText().toString());
//...
}
It seems to me that I've found an error.
The main problem in your code that you do not assign unique values in setId methods. In your case some editTexts and spins can have the same IDs. This is wrong. Every element must have a unique identifier. This is the first what you should correct in your code.
After that you can use my approach. But it seems to me that something wrong in this approach. It is not beautiful ) Try to find best practices in this field.
Few suggestions from my side:
1) try to check whether getText method not giving you empty string"" or null.
2) place your EditText et; to class variable not a local instance.
example public class ExampleActivity extends Activity
{
EditText et;//place it here instead in oncreate methods.
}// or make it final if defining in oncreate.
according to your code, issues seems in your for loop
for(int i=0; i<=etcount; i++){
placed = -1; //reset for next iteration
//try to get number from edittext // which edit text you are trying to access. am sure it is returning null to you.
et.findViewById(i);
placed = Integer.parseInt(et.getText().toString());

setting text in an array of buttons

I'm trying to create a simple application in which there are 30 buttons and I need to initialize their text field.
I created this array of buttons:
Button[][] buttons_arr = new Button[10][3];
To change each button's text I did :
for(i=0..9) //psaudo
for (j=0..29) //psaudo
buttons_arr[i][j].setText(toString(some_int));
The last line is causing some problems. Why and what can I do to solve this issue ?
You are actually looping in 300 times instead of 30 times
try like this
for(i=0..9) //psaudo
for (j=0..2) //psaudo
buttons_arr[i][j].setText(""+some_int);
Try this:
Button[][] b=new Button[10][3];
for(int i=0;i<10;i++)
{
for(int j=0;j<3;j++)
{
b[i][j]=new Button(context);
b[i][j].setText("something");
}
}
I have not tried 2D arrays. But my experience with a similar problem seems to be that buttons_arr[i][j] is still uninitialized. You need to either create a new button:
buttons_arr[1][1] = new Button();
or
buttons_arr[1][1] = (Button)findViewById(R.id.buttonAtPosition1_1);
try this
for(int i=0;i<10;i++){
for(int j=0;j<3;j++)
buttons_arr[i][j].setText(your text);
}

Categories

Resources