Android Align Button Dynamically In RelativeLayout In Fragment - java

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

Related

Android - How to set TextInputEditText dynamically while incrementing the hint and adding a scroll view?

I'm trying to get my button to create a new TextInputEditText field every time the user presses the button. So far I've managed to dynamically add a field but I can't figure out how to increment the hint of the EditText.
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LinearLayout layout = (LinearLayout) findViewById(R.id.holder);
TextInputEditText et = new TextInputEditText(MainActivity.this);
et.setHint("Enter Member + 1");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layout.addView(et,lp);
}
});
For example, I want the hint to increase the number to "Enter Number + X" each time the button is clicked.
You can use the LinearLayout's getChildCount api, the demo code could be:
LinearLayout layout = (LinearLayout) findViewById(R.id.holder);
TextInputEditText et = new TextInputEditText(this);
int childNum = layout.getChildCount();
et.setHint(String.format("Enter Member + %d", childNum+1));
LinearLayout.LayoutParams lp = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layout.addView(et,lp);

Android Studio: Programmatically Instantiating Horizontal Linear Layouts Not Working

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

android - dynamically adding a button to a custom dialogbox

I am writing an android app,
I have an activity, inside it i have a button, and it's on click listener opens a dialog box from a custom XML using the following code:
I would like to add that dialog box another button that is not set in it's XML file.
All the components are excising in the XML and working just fine, the dialog opens but I can't add the b button.
this.addCheer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog d = new Dialog(map.this);
LinearLayout layout = findViewById(R.id.dialog_layout_root);
LayoutInflater layoutInflater = d.getLayoutInflater();
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.cheer_dialog);// custom layout for the dialog
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
d.show();
d.getWindow().setAttributes(lp);
final EditText title = d.findViewById(R.id.cheerDialogText);
ImageButton addCheerOk = (ImageButton) d.findViewById(R.id.addCheerOk);
Button b = new Button(d.getContext());
b.setText("yo");
cheerDialogLayout.addView(b, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
}
I tried to use this example but it does not work for me. What am i doing wrong here?
Thanks!
Just try below code
this.addCheer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog d = new Dialog(map.this);
LayoutInflater layoutInflater = d.getLayoutInflater();
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.cheer_dialog);// custom layout for the dialog
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(d.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.MATCH_PARENT;
d.show();
d.getWindow().setAttributes(lp);
LinearLayout layout = d.findViewById(R.id.dialog_layout_root);
final EditText title = d.findViewById(R.id.cheerDialogText);
ImageButton addCheerOk = (ImageButton) d.findViewById(R.id.addCheerOk);
Button b = new Button(d.getContext());
b.setText("yo");
layout.addView(b, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
}
You were using only findViewById(R.id.dialog_layout_root); instead of d.findViewById(R.id.dialog_layout_root);
Here ll_button is the id of layout which contains the two xml buttons you have.
LinearLayout ll_button = d.findViewById(R.id.ll_button);
LinearLayout.LayoutParams layoutParams = new inearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll_button.addView(b, layoutParams);
Remove your last line.
cheerDialogLayout.addView(b, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));

How to edit/delete objects from another method that were created programatically

I have a method that creates layouts vertically each with 3 buttons aligned horizontally with onClick creating one at a time with each click to a max of 5 layouts. How do I remove those layouts with a button that was created.
public void addTroop(Editable name){
LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);
if (count <= 5)
{
//CREATE NEW LINEAR LAYOUT
LinearLayout addTroopLayout = new LinearLayout(this);
//CREATE LAYOUT PARAMS FOR LAYOUT
LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLayout.bottomMargin = 10;
//STYLE NEW LINEAR LAYOUT
addTroopLayout.setTag("addTroopLayout" + count);
addTroopLayout.setLayoutParams(newLayout);
addTroopLayout.setOrientation(LinearLayout.HORIZONTAL);
//CREATE NEW BUTTONS
Button newTroop = new Button(this);
Button remove = new Button(this);
Button change = new Button(this);
//CREATE LAYOUT PARAMS FOR BUTTONS
LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
//STYLE NEW BUTTONS
newTroop.setText(name);
newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
newTroop.setLayoutParams(newTroopParam);
remove.setTag("rmvBtn" + count);
remove.setText("-");
remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
remove.setLayoutParams(rmvBtnParam);
change.setText("...");
change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
change.setLayoutParams(chngNameParam);
//ADD VIEWS TO NEW LAYOUT
addTroopLayout.addView(newTroop);
addTroopLayout.addView(remove);
addTroopLayout.addView(change);
//ADD NEW LAYOUT TO mainPage LAYOUT
mainPage.addView(addTroopLayout);
//Increment Counter
count++;
}
}
Each time a layout is created it set with the following so that each layout will be named addTroopLayout1, addTroopLayout2, etc etc.
addTroopLayout.setTag("addTroopLayout" + count);
I did the same thing with the remove button
remove.setTag("rmvBtn" + count);
So now how do I access/edit/remove these? Could I do something like
Button rmvBtn1 = (Button) findViewByTag(R.id.rmvBtn1);
rmvBtn1.setOnClickListener(new view.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//REMOVE CREATED LAYOUT
//DECREMENT ALL LAYOUT TAGS BY 1 IF NOT LAST LAYOUT
//DECREMENT count VAR BY ONE
//ERASE ALL VARIABLES ASSOCIATED WITH THIS VIEW
}
});
This code is obviously giving me errors and im sure this is something simple. Thanks.
////////////////////EDIT/////////////////////
Sorry if I wasent clear on what I wanted. So I have created/styled a button using my if statement that is called from a method using an onClick:
Button newTroop = new Button(this);
remove.setTag("rmvBtn" + count);
Count starts at 1 and is incremented in when a button is pressed. Now I want to findViewByTag for that button to use it with something like:enter code here
Button rmvBtn1 = (Button) findViewByTag(rmvBtn1);
rmvBtn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//REMOVE CREATED LAYOUT
//DECREMENT ALL LAYOUT TAGS BY 1 IF NOT LAST LAYOUT
//DECREMENT count VAR BY ONE
//ERASE ALL VARIABLES ASSOCIATED WITH THIS VIEW
}
});
So specifically how to I use a button that was created with my if statement? Do I still have to define it by
Button rmvBtn1 = (Button) findViewByTag(rmvBtn1);
or is there another way I should be doing this?
keep view in remove button, and keep view's parent int view's tag
addTroopLayout.setTag(mainPage);
remove.setTag(addTroopLayout);
and then use it like this
rmvBtn1.setOnClickListener(new view.OnClickListener() {
#Override
public void onClick(View v) {
View willRemove = (View)v.getTag();
LinearLayout mainPage = (LinearLayout)willRemove.getTag();
mainPage.removeView(willRemove);
}
});

Android: how to listen dynamically added button's click?

I have the following code that upon image capture, places a RelativeLayout container, which contains ImageView of the image and Button that is supposed to be the X (Remove) button.
private void addImage(Bitmap photo) {
RelativeLayout rLayout = new RelativeLayout(getApplicationContext()); // Any difference between 'this' and 'getApplicationContext()'?
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParas(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rLayout.setLayoutParams(params);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(photo);
RelativeLayout.LayoutParams bParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
bParams.addRule(RelativeLayout.ALIGN_RIGHT, imageView.getId());
bParams.addRule(RelativeLayout.ALIGN_TOP, imageView.getId());
bParams.setMargins(0, -10, -10, 0);
Button closeButton = new Button(getApplicationContext());
closeButton.setText("X"); // This will be an icon later
closeButton.setBackgroundColor(Color.RED); // For visualization purposes
closeButton.setLayoutParams(bParams);
rLayout.addView(imageView);
rLayout.addView(closeButton);
parentLinearLayout = (LinearLayout) findViewById(R.id.horizontal_scrolling_linear_layout);
parentLinearLayout.addView(rLayout);
}
The ideal scenario is having a close/delete button on top-right corner of the image, that upon click will remove the parent RelativeLayout from it's parent. Some styling and placements in the code might not make sense, I am JUST starting Android Development so any help will be appreciated. I am also including small questions in comments that would help me clear things up in Android Dev.
Question is: How can I capture button (X) click and remove the parent relative layout from the code?
Any help is appreciated, thank you!
Try this:
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
((ViewGroup) rLayout.getParent()).removeView(rLayout);
}
});
I'd start by moving the following line into your Activity's onCreate():
parentLinearLayout = (LinearLayout) findViewById(R.id.horizontal_scrolling_linear_layout);
This helps to reduce unnecessary reassignment as well as clutter. Once that's done, the following should suit your needs.
Button closeButton = new Button(getApplicationContext());
closeButton.setText("X"); // This will be an icon later
closeButton.setBackgroundColor(Color.RED); // For visualization purposes
closeButton.setLayoutParams(bParams);
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (parentLinearLayout != null) {
parentLinearLayout.removeView(rLayout);
}
}
});
Just use
closeButton.setOnClickListener(new OnClickListener(){
//override method
public void onClick(View v) {
//do something
}
});
In addition,you can't remove the parent RelativeLayout ,because any view must be included by viewGroup.
And the difference between "this" and "getApplicationContext()" as you mentioned at the beginning is:
this == yourActivity.this ,it is activity's instance. However,getApplicationContext() will get Application's instance.
// Try this way,hope this will help you to solve your problem...
private void addImage(Bitmap photo) {
RelativeLayout rLayout = new RelativeLayout(getApplicationContext());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
rLayout.setLayoutParams(params);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(photo);
RelativeLayout.LayoutParams bParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
bParams.addRule(RelativeLayout.ALIGN_RIGHT, imageView.getId());
bParams.addRule(RelativeLayout.ALIGN_TOP, imageView.getId());
bParams.setMargins(0, -10, -10, 0);
Button closeButton = new Button(getApplicationContext());
closeButton.setText("X"); // This will be an icon later
closeButton.setBackgroundColor(Color.RED); // For visualization purposes
closeButton.setLayoutParams(bParams);
closeButton.setTag(0,parentLinearLayout);
closeButton.setTag(1,rLayout);
closeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
LinearLayout parentLinearLayout = (LinearLayout)view.getTag(0);
RelativeLayout rLayout = (RelativeLayout)view.getTag(1);
parentLinearLayout.removeView(rLayout);
}
});
rLayout.addView(imageView);
rLayout.addView(closeButton);
parentLinearLayout = (LinearLayout) findViewById(R.id.horizontal_scrolling_linear_layout);
parentLinearLayout.addView(rLayout);
}

Categories