Android Studio: Programmatically Instantiating Horizontal Linear Layouts Not Working - java

Finally found a workaround: I decided to just use a table with a single row and then set stretchAllColumns to true. This means it just mimics a horizontal layout with spread-out views.
I am trying to instantiate a horizontal linear layout at runtime and I would like the elements in the layout to spread out along the full width of the layout. I would also like everything to be center-vertical aligned. This is currently what I've got:
LinearLayout tertiaryLinearLayout = new LinearLayout(getActivity());
tertiaryLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
tertiaryLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
tertiaryLinearLayout.setGravity(Gravity.FILL_HORIZONTAL);
This instantiates the layout but the elements in it don't correctly fill the full width of it. I am also not sure how I can get them to be center-vertical aligned without changing setGravity to
tertiaryLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
This TextView is one of the five elements I add to the layout:
TextView dash = new TextView(getActivity());
dash.setText("-");
Two of the elements are ImageViews and the other three are TextViews. Here is how it looks currently:
https://i.stack.imgur.com/MGLyJ.jpg
EDIT:
The overall structure is a ScollView with a vertical LinearLayout. This LinearLayout holds lots of other vertical LinearLayouts, each with a horizontal LinearLayout. Hope that makes sense.
The parent view of tertiaryLinearLayout is here:
LinearLayout secondaryLinearLayout = new LinearLayout(getActivity());
secondaryLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
secondaryLinearLayout.setOrientation(LinearLayout.VERTICAL);
...
secondaryLinearLayout.addView(tertiaryLinearLayout);
EDIT 2:
Here is my full code:
...
final LinearLayout linearLayout = root.findViewById(R.id.leagueLinearLayout);
List<Game> currentYearCategory = MainActivity.yearCategories.get(0);
for (int i = 0; i < currentYearCategory.size(); i++) {
TextView textView = new TextView(getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
textView.setLayoutParams(params);
textView.setText(currentYearCategory.get(i).date);
linearLayout.addView(textView);
}
seekBarChange(linearLayout, root, 0);
// Set up seek bar
SeekBar yearSeekBar = root.findViewById(R.id.yearSeekBar);
yearSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekBarChange(linearLayout, root, progress);
}
...
...
private void seekBarChange(LinearLayout linearLayout, View root, int progress){
TextView yearTextView = root.findViewById(R.id.yearTextView);
String newText = (1890 + progress * 10) + " - " + (1899 + progress * 10);
yearTextView.setText(newText);
final List<Game> currentYearCategory = MainActivity.yearCategories.get(progress);
linearLayout.removeAllViews();
for (int i = 0; i < currentYearCategory.size(); i++) {
// Create views
LinearLayout secondaryLinearLayout = new LinearLayout(getActivity());
secondaryLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
secondaryLinearLayout.setOrientation(LinearLayout.VERTICAL);
View separatorView = new View(getActivity());
separatorView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50));
TextView date = new TextView(getActivity());
date.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
date.setText(currentYearCategory.get(i).date);
LinearLayout tertiaryLinearLayout = new LinearLayout(getActivity());
tertiaryLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
tertiaryLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
tertiaryLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
ImageView homeImage = new ImageView(getActivity());
homeImage.setLayoutParams(new ViewGroup.LayoutParams(150, 150));
if (currentYearCategory.get(i).celticIsHome){
homeImage.setBackgroundResource(R.drawable.celtic_logo);
} else {
homeImage.setBackgroundResource(R.drawable.rangers_logo);
}
TextView homeScore = new TextView(getActivity());
homeScore.setText(currentYearCategory.get(i).fullTimeScore.substring(0, 1));
TextView dash = new TextView(getActivity());
dash.setText("-");
TextView awayScore = new TextView(getActivity());
awayScore.setText(currentYearCategory.get(i).fullTimeScore.substring(2));
ImageView awayImage = new ImageView(getActivity());
awayImage.setLayoutParams(new ViewGroup.LayoutParams(150, 150));
if (currentYearCategory.get(i).celticIsHome){
awayImage.setBackgroundResource(R.drawable.rangers_logo);
} else {
awayImage.setBackgroundResource(R.drawable.celtic_logo);
}
// Add views
tertiaryLinearLayout.addView(homeImage);
tertiaryLinearLayout.addView(homeScore);
tertiaryLinearLayout.addView(dash);
tertiaryLinearLayout.addView(awayScore);
tertiaryLinearLayout.addView(awayImage);
secondaryLinearLayout.addView(separatorView);
secondaryLinearLayout.addView(date);
secondaryLinearLayout.addView(tertiaryLinearLayout);
final int gameNum = i;
secondaryLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGameActivity(currentYearCategory, gameNum);
}
});
linearLayout.addView(secondaryLinearLayout);
}
}
Any help would be greatly appreciated, thanks!

I guess that the PARENT view that the tertiaryLinearLayout will be added to is wrap_content for the layout_width. Try to make its width match_parent. You should have a look on this tutorial at 2:52s

Related

How to set one view in vertical linearlayout in top and another in bottom programmatically?

I'm trying to create programmatically parent LinearLayout
and 3 TextViews.
One TextView must be aligned in top left, the second one in the center of parent
and the third one to the right and bottom of my screen. Everything must be done in code.
I'm almost done, but there is still some problem.
All my 3 views are on the top
My code:
public class ActivityFour extends AppCompatActivity {
private LinearLayout mLinearLayout;
private TextView tv1;
private TextView tv2;
private TextView tv3;
private static final int TV_ID1 = 101;
private static final int TV_ID2 = 102;
private static final int TV_ID3 = 103;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLinearLayout = new LinearLayout(this);
mLinearLayout.setOrientation(LinearLayout.VERTICAL);
ViewGroup.LayoutParams llParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
setContentView(mLinearLayout, llParams);
LinearLayout.LayoutParams linlayout_params1 =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams linlayout_params2 =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams linlayout_params3 =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
linlayout_params1.setMargins(16,16,16,16);
tv1 = new TextView(this);
tv1.setId(TV_ID1);
linlayout_params1.gravity = Gravity.START;
linlayout_params1.gravity = Gravity.TOP;
mLinearLayout.addView(tv1, linlayout_params1);
tv1.setText("TextView number ONE");
linlayout_params2.setMargins(16,16,16,16);
tv2 = new TextView(this);
tv2.setId(TV_ID2);
linlayout_params2.gravity = Gravity.CENTER;
mLinearLayout.addView(tv2, linlayout_params2);
tv2.setText("TextView number TWO");
linlayout_params3.setMargins(16,16,16,16);
tv3 = new TextView(this);
tv3.setId(TV_ID3);
linlayout_params3.gravity = Gravity.END;
mLinearLayout.addView(tv3, linlayout_params3);
tv3.setText("TextView number THREE");
}
}
After adding the weight property to all view.params it looks like this
In order to make the LinearLayout fill all the available space, you need to set the android:layout_weight attribute on the middle child View. You can do it programmatically by using a Constructor which takes the weight as third parameter:
LinearLayout.LayoutParams linlayout_params2 =
new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 1);
First of all no need to create liner layout for all textview you can do like this:
in xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/test"
tools:context=".activity.TestActivity"/>
and in activity file :
LinearLayout layout = findViewById(R.id.test);
TextView product_1 = new TextView(this);
product_1.setText("Product 1");
product_1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0,1f));
layout.addView(product_1);
TextView product_2 = new TextView(this);
product_2.setText("Product 2");
product_2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0,1f));
product_2.setGravity(Gravity.CENTER);
layout.addView(product_2);
TextView product_3 = new TextView(this);
product_3.setText("Product 3");
product_3.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0,1f));
product_3.setGravity(Gravity.END|Gravity.BOTTOM);
layout.addView(product_3);

Cannot make the button wider by Java Code

I don't know what is the problem. I am creating the simple phone-book, so i have name of abonent, image and call button under the name. And when i try to set width with the layoutParams parameter for button, it doesn't change anything, btn.setWidth(); doesn't work either.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout linear = (LinearLayout)findViewById(R.id.linear);
LinearLayout.LayoutParams sublparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams childparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LinearLayout.LayoutParams imageparams = new LinearLayout.LayoutParams(200, 200);
linear.setOrientation(LinearLayout.VERTICAL);
for(int i = 0; i < 10 ; i++){
LinearLayout sublinear = new LinearLayout(this);
Button btn = new Button(this);
ImageView img = new ImageView(this);
TextView txt = new TextView(this);
img.setImageResource(R.drawable.img);
txt.setText("Abonent " + (i+1));
btn.setBackgroundColor(getColor(R.color.mygreen));
btn.setText("+3800000");
txt.setLayoutParams(childparams);
btn.setLayoutParams(imageparams);
img.setLayoutParams(imageparams);
linear.addView(txt);
sublinear.addView(img);
sublinear.addView(btn);
linear.addView(sublinear, sublparams);
}
}
}
result of programm, green vertical lines are buttons, that i cannot to make wider
your button is using LayoutParams to set width and heigth so you need to change this properties here (LinearLayout.LayoutParams(widht, height)):
LinearLayout.LayoutParams imageparams = new LinearLayout.LayoutParams(500, 300);
and the size of your button must change, because you are setting this values.
btn.setLayoutParams(imageparams);

Android Spinner with description-label different heights

I'm using a spinner for selecting amounts to re-calculate quantities of recipe-ingredients.
I have a horizontal LinearLayout which I add a label(TextView) to to describe the spinner and then the spinner.
When I first load the activity, the label is positioned a bit higher than the spinner, when I select an item, it corrects its height.
How do I fix that?
Code of my spinner-loading method:
// Horizontal LinearLayout for displaying label + spinner
LinearLayout spinnerLayout = new LinearLayout(getApplicationContext());
spinnerLayout.setOrientation(LinearLayout.HORIZONTAL);
spinnerLayout.setLayoutParams( new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
// Textview for description
TextView lblAmount = new TextView(getApplicationContext());
lblAmount.setText("Quantity:");
lblAmount.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
lblAmount.setTextColor(Color.parseColor("#161618"));
spinnerLayout.addView(lblAmount);
// add spinner
ArrayList<Integer> spinnerArray = new ArrayList<Integer>();
for(int i = 1; i<= 10; i++) {
spinnerArray.add(i);
}
final Spinner spnIngredientQuantity = new Spinner(this);
ArrayAdapter<Integer> spinnerArrayAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spnIngredientQuantity.setAdapter(spinnerArrayAdapter);
spnIngredientQuantity.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
spinnerLayout.addView(spnIngredientQuantity);
if(firstLoad) {
spnIngredientQuantity.setSelection(spinnerArrayAdapter.getPosition(recipe.getDefaultAmount()));
firstLoad = false;
}
spnIngredientQuantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
reloadIngredients((int) spnIngredientQuantity.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Use default Quantity
}
});
scrollLayout.addView(spinnerLayout);
I think it might be the fact, that I add the spinnerLayout with height set to WRAP_CONTENT, so it's smaller when the TextView comes in. later, the spinner takes more space in height, but the textView doesn't get updatet.
Could that be the problem?
edit: attached screenshot
I don't know what actually caused the problem,but I fixed it with centering the textView horizontally:
spinnerLayout.setGravity(Gravity.CENTER_VERTICAL);

Android Align Button Dynamically In RelativeLayout In Fragment

I am trying to align the button vertically that are generated dynamically in a for loop within a RelativeLayout fragment, but the buttons are overlapping at the same position, I have looked through alot of the other posts and I still don't know how to fix it, helpppppp
I know use linearLayout will solve the problem, but the buttons are the wrong size and position, and for some reason I can't add the linearLayout to the relativeLayout. I have pasted 2 code sample, and I need a solution for 1 of them. Thanks in advance.
Below is my code (Attempt 1: Align button in relative layout):
View view = inflater.inflate(R.layout.home, container, false);
RelativeLayout relativeLayout = new RelativeLayout(getActivity().getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
List<String> test_list = Arrays.asList("sup1", "sup2", "sup3");
for (int i = 0; i < test_list.size(); i++) {
final String test_name = test_list.get(i);
Button button = new Button(getActivity());
button.setText("Test" + test_name + " " + i);
button.setId(i);
if(i > 0){
lp.addRule(RelativeLayout.RIGHT_OF, (i-1));
}
relativeLayout.addView(button, lp);
button.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
FragmentManager fragmentmanager = getFragmentManager();
FragmentTransaction transaction = fragmentmanager.beginTransaction(); // allows attach,detach,etc
transaction.replace(R.id.DB2Home, newFragment, "ChooseCategory").addToBackStack(null).commit();
}
});
}
((ViewGroup) view).addView(relativeLayout);
return view;
(Attempt 2: Align button in linear layout and add to relative layout)
View view = inflater.inflate(R.layout.home, container, false);
LinearLayout linearLayout = new LinearLayout(getActivity().getApplicationContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
List<String> test_list = Arrays.asList("sup1", "sup2", "sup3");
for (int i = 0; i < test_list.size(); i++) {
final String test_name = test_list.get(i);
Button button = new Button(getActivity());
button.setText(test_name);
button.setId(i);
linearLayout.addView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentmanager = getFragmentManager();
FragmentTransaction transaction = fragmentmanager.beginTransaction(); // allows attach,detach,etc
transaction.replace(R.id.DB2Home, newFragment,"ChooseCategory").addToBackStack(null).commit();
}
});
}
// Doesn't work for relative layout
// RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.homescreen);
//relativeLayout.addView(linearLayout);
//((ViewGroup) view).addView(relativeLayout);
((ViewGroup) view).addView(linearLayout);
return view;
You can get to it via code:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params); //causes layout update

How to set align of view without xml in android

I don't use xml in my UI.
My code of mainlayout:
public class MainActivity extends ActionBarActivity {
LinearLayout LinLay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
this.setContentView(sv);
LinLay = new LinearLayout(this);
LinLay.setOrientation(LinearLayout.VERTICAL);
LinLay.setBackgroundColor(Color.parseColor("#000000"));
sv.addView(LinLay);
And adding a Edittext:
EditText txt = new EditText(this);
txt.setBackgroundColor(Color.parseColor("#ff9a16"));
txt.setHint("Txt(0,0)");
LayoutParams txtParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
txtParams.width = 300;
txtParams.height = 70;
txtParams.leftMargin = 0;
txtParams.topMargin = 0;
txt.setLayoutParams(txtParams);
LinLay.addView(txt);
Finally adding a Button:
Button btn = new Button(this);
btn.setBackgroundColor(Color.parseColor("#cb0016"));
btn.setText("Btn(0,0)");
LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
btnParams.width = 300;
btnParams.height = 70;
btnParams.leftMargin = 0;
btnParams.topMargin = 0;
btn.setLayoutParams(btnParams);
LinLay.addView(btn); }
The Edittext's must be X position = 0 and Y position = 0 of MainScreen.
The Button's must be X position = 0 and Y position = 0 of MainScreen.
But the Button taking referance is the Edittext and it takes position in X:0,Y:70 of MainScreen.
The program screen: prntscr.com/4ixo7z
If my LinearLayout that's LinLay is Horizontal, the button takes position in X:300,Y:0 of MyScreen. I want to taking position in MainScreen. I don't want to taking referance. Help me.
The Horizontal screen: prntscr.com/4ixo8i
Change your LinearLayout and use RelativeLayout, remove orientation. add your product relatively, this will solve your issue.

Categories