Creating Linear Layout with TextViews using a for loop - java

I was wondering if there is a way to dynamically create an additional linear layout with a textview within a predefined liner layout. THis is my code so you get the gist of what I am asking:
LinearLayout MainLL= (LinearLayout) findViewById(R.id.myLayoutId);
for(int i=0; i<5; i++)
{
LinearLayout childLL= new LinearLayout(this);
childLL.setOrientation(LinearLayout.VERTICAL);
childLL.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
childLL.setGravity(Gravity.LEFT);
TextView text = new TextView(this);
text.setText("The Value of i is :"i);
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
childLL.addView(text);
MainLL.addView(childLL);
}
My problem is that I am only getting "The Value of i is :0" as the output, i.e. the first instance.
Any help would be much appreciated

You don't need to wrap the TextView inside another LinearLayout, you can do just:
LinearLayout MainLL= (LinearLayout) findViewById(R.id.myLayoutId);
for(int i=0; i<5; i++){
TextView text = new TextView(this);
text.setText("The Value of i is :"+i); // <-- does it really compile without the + sign?
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
MainLL.addView(text);
}

Everything you are doing is correct just make it
childLL.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
because your parent layout is filled by 1st view because of that you can not see other view.
and yes
text.setText("The Value of i is :"+i); //add + sign

Yes, if you greatly need to wrap another LinearLayout before wrapping the TextView.
Please try this code:
childLL.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
This will ensure the wrapped LinearLayout has the same weight, so all the views will be displayed on the screen.

Related

Android - creating a few frame layout and align them with Gravity programmatically

I have an array of results and i want to display each one of them in a different FrameLayout. My activity already contains a ScrollView that contains a RelativeLayout. I am using a 'for' to create each FrameLayout but right now every one of the results' parameters displayed on the same spot - This is probably because the gravity parameters are not set correctly.
This is my code:
for (int i = 0; i < results.length; ++i) {
LayoutParams textViewsLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
Gravity.CLIP_VERTICAL);
LayoutParams dividerLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, 1,
Gravity.CLIP_VERTICAL);
LayoutParams frameLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.CLIP_VERTICAL);
frameLayoutParams.setMargins(5, 5, 5, 5);
//Initializing text views
TextView domain = new TextView(SinglePhotoResults.this);
domain.setText(results[i].getDomain());
domain.setTextSize(22);
domain.setGravity(Gravity.CLIP_VERTICAL);
domain.setTextColor(Color.parseColor("#1A1AFF"));
domain.setLayoutParams(textViewsLayoutParams);
TextView url = new TextView(SinglePhotoResults.this);
url.setText(results[i].getURL());
url.setTextSize(22);
url.setGravity(Gravity.CLIP_VERTICAL);
url.setTextColor(Color.parseColor("#00CC00"));
url.setLayoutParams(textViewsLayoutParams);
View divider = new View(SinglePhotoResults.this);
divider.setBackgroundColor(Color.parseColor("#00ff00"));
divider.setLayoutParams(dividerLayoutParams);
TextView percents = new TextView(SinglePhotoResults.this);
Integer percentage = results[i].getPrecents();
percents.setText(percentage.toString());
percents.setTextSize(22);
percents.setGravity(Gravity.CLIP_VERTICAL);
percents.setTextColor(Color.parseColor("#000000"));
percents.setLayoutParams(textViewsLayoutParams);
TextView copiedWords = new TextView(SinglePhotoResults.this);
Integer copiedWordsNum = results[i].getNumberOfCopiedWords();
copiedWords.setText(copiedWordsNum.toString());
copiedWords.setTextSize(22);
copiedWords.setGravity(Gravity.CLIP_VERTICAL);
copiedWords.setTextColor(Color.parseColor("#000000"));
copiedWords.setLayoutParams(textViewsLayoutParams);
//Initializing frame layout
FrameLayout frameLayout = new FrameLayout(SinglePhotoResults.this);
frameLayout.setLayoutParams(frameLayoutParams);
frameLayout.setBackgroundColor(Color.parseColor("#ffffff"));
frameLayout.setPadding(5, 5, 5, 5);
frameLayout.setForegroundGravity(Gravity.CLIP_VERTICAL);
//Adding views to FrameLayout
frameLayout.addView(domain);
frameLayout.addView(url);
frameLayout.addView(divider);
frameLayout.addView(percents);
frameLayout.addView(copiedWords);
////Adding frameLayout to relativeLayout
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.singlePhotoResultRelativeLayout);
relativeLayout.addView(frameLayout);
}
I want it to be displayed one rectangle after another.
How can i set the Gravity parameters correctly of the FrameLayouts and inside it?
Instead of using Relative layout you should use LinearLayout. If you still want to use Relative layout you need to specify below which element you put your next element.
(I would suggest moving to listview instead).

Issue with Button in AlertDialog (Floating off screen)

Here's an image of what my issue looks like:
That box at the bottom is the top half of a button. Whenever I've got too many Stock Options in the dialog box, it first forces the button off screen, THEN it scrolls.
I want the button fixed at the bottom of the dialog and then have the scrolling happen.
Here's the code:
public void buyStock(View view){
Context context = getApplicationContext();
//create ScrollView to hold everything
ScrollView scrollView = new ScrollView(context);
//generate content for dialog
LinearLayout dialogContainer = new LinearLayout(context);
dialogContainer.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 400, 1);
dialogContainer.setLayoutParams(params);
dialogContainer.setPadding(15, 15, 0, 15);
dialogContainer.setBackgroundColor(Color.WHITE);
//each hotel stock options
for (int i = 0; i < hotels.size(); i++) {
Hotel testHotel = hotels.get(i);
testHotel.setPrice(200);
View stockPicker = getStockPicker(testHotel);
LinearLayout.LayoutParams pickerParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 100, 1.0f);
pickerParams.gravity = Gravity.LEFT;
stockPicker.setLayoutParams(pickerParams);
dialogContainer.addView(stockPicker);
stockPicker.setBackgroundColor(0xffffff);
}
scrollView.addView(dialogContainer);
LinearLayout dialogLayout = new LinearLayout(context);
dialogLayout.setOrientation(LinearLayout.VERTICAL);
Button buyButton = new Button(context);
LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100);
buyButton.setLayoutParams(buttonParams);
LinearLayout buttonLayout = new LinearLayout(context);
buttonLayout.addView(buyButton);
dialogLayout.addView(scrollView);
dialogLayout.addView(buttonLayout);
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.AppTheme);
AlertDialog.Builder buyStockDialog = new AlertDialog.Builder(ctw);
buyStockDialog.setTitle("Buy Stock: ");
buyStockDialog.setView(dialogLayout);
buyStockDialog.show();
}
Make dialogLayout a RelativeLayout, and then declare buttonParams as a RelativeLayout.LayoutParams (layout params are declared according the parent viewgroup type, which for buyButton is now a RelativeLayout). Your also going to need to declare a RelativeLayout.LayoutParams for scrollView.
note: This code is in c#/monodroid, not raw java/android, so some quick porting of some of the methods and constants may need to be required, but shouldn't be too time consuming.
If this doesn't work out exactly trying experimenting with other combinations of the RelativeLayout position rules and/or gravity. Let me know if it doesn't work out.
RelativeLayout.LayoutParams scrollParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, some_height);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, 100);
Then, add these statements to control where scrollView and buyButton are positioned
scrollParams.AddRule(LayoutRules.AlignParentLeft);
scrollParams.AddRule(LayoutRules.AlignParentTop);
buttonParams.AddRule(LayoutRules.Below, scrollView.Id);
The for the getting the button on the bottom of the screen, try one of two things
buttonParams.AddRule(LayoutRules.AlignParentBottom);
or
buyButton.Gravity = Gravity.BOTTOM
Try explicitly setting a fixed height to the scrollView
scrollView.LayoutParameters.Height = HEIGHT;
I think it defaults to WRAP_CONTENT if not specified, and is why its scaling.
You may have to set it in a layout file if you cant from code
<ScrollView
android:id="#+id/scroll_view_1
android:layout_width="wrap_content"
android:layout_height="100"/>
and then change
ScrollView scrollView = new ScrollView(context);
to
ScrollView scrollView = findViewById(R.Id.scroll_view_1, this);
Try wrapping the scrollView in another LinearLayout, and set this new layout's height to a fixed width that keeps the button low enough to your liking. You can actually replace the Scrollview with a ListView, but don't do this until after at least trying to get this fix working first. ListViews scroll, but you'd still face this problem without this fix.
To fix the new issue you mentioned below (with some quick and dirty code, you should use trial and error to fix it correctly), try the following
//each hotel stock options
for (int i = 0; i < hotels.size(); i++)
{
// ...
}
if( hotels.size() < numberOfItemsNeededForCorrectView )
{
for( int i=0; i < numberOfItemsNeededForCorrectView - hotels.size(); i++ )
{
View blankView = new View(context);
LinearLayout.LayoutParams viewParams = new LinearLayout.LayoutParams(1, 100);
blankView.setLayoutParams(viewParams);
blankView.setViewState(ViewState.INVISIBLE);
dialogContainer.addView(stockPicker);
}
}
You can try replacing your scrollView with a list view still and see if that fixes things. You can also try tweaking layout and gravity settings until you get it, or trying introducing other layouts or reorganizing your layouts (or using RelativeLayout, its really not that bad).
So, now in 2022 I've also had this problem. I've just set fixed size for ScrollView in fragment layout xml-file. When you have this problem, you can set, for example, 150dp or 200dp and be happy! And for more convenience, you can create special layout for landscape screen orientation and set fixed layout_height size there. I'm really confused that there's no information about this problem besides this page on the Internet.
<ScrollView
android:layout_width="match_parent"
android:layout_height="200dp">
<!--your view into scrollView here-->
</ScrollView>

Android set gravity of a textview dynamically

I dynamically added horizontal layouts to my activity, and I am trying to put textviews inside of them.
The problem is, I can't manage to put some textviews To the right and some to the left.
I tried textview.setgravity, but it just changed the place of the text inside the textview instead of moving the textview itself.
Edit : here is some of my code to help you get an idea :
for(int i=0;i<nbelem;i++){ //génération des boutons des commandes
layouts[i] = new RelativeLayout(this);
layouts[i].setClickable(true); //toute la zone est cliquable
layouts[i].setId(i);
layouts[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 150));
Info[i] = new TextView(this);
Info[i].setClickable(true);
Info[i].setId(i);
Info[i].setText("Pizza 4 fromages x2 \n Pizza chevre x2");
Info[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
layouts[i].addView(Info[i]);
Numcom[i] = new TextView(this);
Numcom[i].setClickable(true);
Numcom[i].setId(i);
Numcom[i].setText("n°1522");
Numcom[i].setGravity(Gravity.RIGHT | Gravity.TOP);
Numcom[i].setTextSize(12);
Numcom[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,50));
It sounds that RelativeLayout may suit your needs and save you lots of nested LinearLayouts which are not recommended (performance wise).
You have to set a layout gravity to the LinearLayout that contains your textview.
LayoutParams lp = new LayoutParams();
lp.gravity= Gravity.CENTER_HORIZONTAL;
textview1.setLayoutParams(lp);
Be sure that you use LinearLayout.LayoutParams

ScrollView in android

I have a TableLayout, in which rows are dynamically created, thus it may cross the limited screen size. To avoid this I am trying to add a scroll view after creating the table layout as:
TableLayout tl = (TableLayout) findViewById(R.id.tableLayout1);
ScrollView sv = new ScrollView(this);
tl.addView(sv);
for (i = 0; i < count; i++) {
TableRow tr = new TableRow(this);
.
.
.
. //finally iam adding this table row to layout.
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(getApplicationContext(),
SmsActivity.class);
// setMessageBody((String) tvf.getContentDescription());
// submit.setEnabled(false);
String messageText = (String) valueTV.getText();
String dateText = (String) labelTV.getText();
myIntent.putExtra("messageText",dateText+"\n"+message);
startActivity(myIntent);
}});
}
However the application is getting force closed if the number of rows increases more than the size of display.
My log cat shows the error as
06-28 14:41:49.533: ERROR/AndroidRuntime(1256): Caused by: java.lang.StringIndexOutOfBoundsException
What is the problem and how can I fix it?
You need to add the TableLayout to the ScrollView, and not the other way around.
ScrollView can only have one child and will throw an IllegalStateException if you try to add more than one. Typical practice is a ScrollView with another view inside it containing the views over which you wish to scroll.
Having said that, you appear to be getting a different sort of IllegalStateException so I'm not 100% sure that this is the issue.
In my view, though, the real solution is to not dynamically populate a ScrollView but instead use a ListView, which is explicitly intended for just this sort of thing. It's a little more work but very rewarding in terms of performance and scalability.

How to programmatically center progress bar in layout?

I want to programatically center my progress bars in code. Here is my code:
LinearLayout streamLayout = new LinearLayout(this);
streamLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
streamLayout.setOrientation(LinearLayout.VERTICAL);
streamLayout.setGravity(Gravity.CENTER);
LinearLayout newsLayout = new LinearLayout(this);
streamLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
streamLayout.setOrientation(LinearLayout.VERTICAL);
streamLayout.setGravity(Gravity.CENTER);
mSwipeView.addView(streamLayout);
mSwipeView.addView(newsLayout);
mSwipeView.addView(new LinearLayout(this));
((LinearLayout) mSwipeView.getChildContainer().getChildAt(0)).addView(streamListView);
((LinearLayout) mSwipeView.getChildContainer().getChildAt(0)).addView(streamProgressBar);
((LinearLayout) mSwipeView.getChildContainer().getChildAt(1)).addView(newsListView);
((LinearLayout) mSwipeView.getChildContainer().getChildAt(1)).addView(newsProgressBar);
((LinearLayout) mSwipeView.getChildContainer().getChildAt(2)).addView(chartImageView);
How can I get the progress bar to be in the centered vertically, and horizontally in my layout?
Try using LinearLayout.layoutParams and setting them to the view. they contain a field gravity that you can set to Gravity.CENTER or similar.
See This Link
View.setScaleType(ScaleType.CENTER_INSIDE);// or fitCenter
Hope it helps :)

Categories

Resources