I am dynamically adding controls in my activity. simultaneously i'm adding a editbox and button, but facing some issue in image alignment.
Here is my code which ads the editText and Button and returns to the linear layout which is vertical in alignment.
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(0);
final EditText textView = new EditText(this);
textView.setLayoutParams(lparams);
textView.setSingleLine(true);
final LayoutParams lparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
textView.setLayoutParams(lparams1);
if(id == R.id.new_alternate_number_button)
{
if(contactNumber == "")
{
textView.setHint("Enter contact Number");
}
else
{
textView.setText(contactNumber);
}
textView.setInputType(InputType.TYPE_CLASS_PHONE); //to popup numpad
}
else
{
if(contactEmailID == "")
{
textView.setHint("Enter Email ID ");
}
else
{
textView.setText(contactEmailID);
}
}
button.setBackgroundResource(R.drawable.ic_delete);
button.setBackgroundResource(R.drawable.ic_delete);
button.setOnClickListener(deleteView);
layout.addView(textView);
layout.addView(button);
textView.post(new Runnable() {
public void run() {
textView.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textView, InputMethodManager.SHOW_IMPLICIT);
}
});
return layout;
In my XML file i have declared linear layout which is vertical in alignment i.e icon should be at the end of screen and EditText should be left aligned.. also i need a space between EditText and image..
Thanks in advance
Your LayoutParams is set to WRAP_CONTENT for Width instead of FILL_PARENT (or MATCH_PARENT).
A "pattern" that I use in similar cases is that even though I'm dynamically adding a new row/section, I still keep they layout in an xml file for that row, and then I dynamically inflate and find the elements by id, and bind to them. Sort of like how we deal with List Items except in this case, you are not using a list.
By keeping the layout in the XML file, it'll be easier to prototype what you want to see, add padding etc. And you can even use a RelativeLayout if you can't get the LinearLayout to work. Again, you can do all of this in code, but doing layout in the XML offers more flexibility (and is simpler to deal with in my mind)
This how you can go about adding space between the Button and EditText:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(50, 0, 0, 0); // Adding margin to the left of your button
Button yourButton = new Button(this);
yourButton.setText("some text");
linearLayout.addView(yourButton, layoutParams);
The sequence of parameters in setMargins method:
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
Know more about setMargins method here.
Now that I realize your requirements properly (at least I guess so) I have another answer for you. Keep me updated about how it helps.
You will have to specify weight for the elements. Let's say total weightSum of your layout is 8, then if you specify weight of the EditText as 7, it will take 7/8th of the total space. And set wight of the Button as 1, so it will take 1/8th of the space. I am using 8 just as an example, you can change it to any number you want, do some trial and error see what weights are suiting your needs the best.
Also, the weights are in float, so don't forget the "f" after the number, like 1f and 7f:
(Again, I am not near my dev machine so there may be some errors. But this should work.)
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 7f);
// Last parameter 6f defines weight. So yourEditText will take 7/8th of the space
linearLayout.addView(yourEditText, layoutParams);
layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
// Last parameter 6f defines weight. So yourEditText will take 1/8th of the space
linearLayout.addView(yourButton, layoutParams);
Let's see how this helps. :)
Related
Click here to see the image
In the profile page of my application, I want to have an interest section as shown in the image. The user has a list of interest under his profile. I want to show his/her interests inside a horizontal LinearLayout. I have created an array of TextViews and add them dynamically inside the parent LinearLayout, but I do not want to add the TextViews when there is no more space. Instead, I want to add a TextView showing the number of remaining interests.
As shown in the picture (use the image link), the user had 24 interests, 4 of them fit horizontally on the same line and last TextView(+20) shows the number of remaining interests on the same line.
String interestList[]={"Travel","Music","Photography","Sports","Dance","Animals","SciFi Movies"};
int interestWidth =0, parentWidth=interestLinearLayout.getWidth();
for(String interest: interestList) {
TextView textView = new TextView(MainActivity.this);
textView.setBackground(getResources().getDrawable(R.drawable.interests_bg));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(2,0,10,2);
textView.setLayoutParams(params);
textView.setPadding(2, 2, 2, 2);
textView.setText(" "+interest+" ");
textView.setTextColor(getResources().getColor(R.color.white));
textView.setIncludeFontPadding(true);
interestWidth += textView.getWidth();
if(interestWidth<parentWidth) //both are 0 on first iteration of loop???
interestLinearLayout.addView(textView);
else
break;
}
You can add views dynamically but first you need a reference to the parent view to which you want to add a view.
You can do this by just using findViewById. Assuming it's a linear layout,
LinearLayout parent = findViewById(R.id.parent);
// Then create a textview
TextView textView = new TextView(this);
// Add the view to the parent
parent.addView(textView);
And that's it! To change properties about the TextView, you can use TextView getters and setters. If you want to change the margin, padding or height of width of the TextView, use LayoutParams
// Remember that I'm using LinearLayout.LayoutParams because the parent of the ttextview is a LinearLayout
LinearLayout.LayourParams params = textView.getLayoutParams();
// Remember these values are in pixels
params.height = 100;
params.width = 200;
There are tons of problems using this method, such as setting height and width in pixels instead of dps. And writing a lot of code when you could have done it in xml. You can however make this much easier by creating an xml file in your res/layout and then inflating it and finally adding it to the parent.
You can do this by -
// First get the layout inflater
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView textView = inflater.inflate(R.layout.myTextView, null);
linearLayout.addView(textView);
Finally addressing your problem about adding only enough views that the linearLayout doesn't go beyond the screen width.
The easiest solution is, to loop through the interest list and in every iteration of the loop, measure the combined width of the TextViews created and then checking whether it exceeds the width of the linearLayout.
It would look similar to this -
int combinedWidth = 0;
int linearLayoutWidth = linearLayout.getMeasuredWidth();
for(String interest : interests){
TextView view = inflater.inflate(R.layout.textview, null);
combinedWidth += textView.getMeasuredWidth();
view.setText(interest);
if(combinedWidth > linearLayoutWidth){
// No need to add more views
break;
}else{
linearLayout.addView(textView);
}
}
However, the above solution may or may not work depending on when it is executed. So post the activity code along with the xml file so that I can better answer your question.
The interestWidth and parentWidth are initially 0 because they have not been laid out when getWidth is called.
get width for dynamically created textViews
The above link helped me getting width of dynamically created textViews from interestList.
And by using ViewTreeObserver on interestLinearLayout I was able to get the width of LinearLayout after it was laid out.
Finally, the above code should be modified as below to add textViews from JAVA inside a LinearLayout.
final LinearLayout interestLinearLayout = findViewById(R.id.interests);
interestLinearLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
interestLinearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
String interestList[]={"Travel","Music","Photography","Sports","Dance","Animals","SciFi Movies"};
int interestWidth =0;
int parentWidth = interestLinearLayout.getWidth(); // got width inside view tree observer for linearlayout
for(String interest: interestList) {
TextView textView = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.setMargins(2,0,10,2);
textView.setLayoutParams(params);
textView.setPadding(2, 2, 2, 2);
textView.setText(interest);
textView.setIncludeFontPadding(true);
textView.measure(0,0); //using approach mentioned in link to get width of text views
interestWidth += textView.getMeasuredWidth();
if(interestWidth<parentWidth)
interestLinearLayout.addView(textView);
else
break;
}
}
});
To create a LinearLayout,
LinearLayout layout = new LinearLayout(MainActivity.this);
To set background color of a layout,
layout.setBackgroundColor(Color.parseColor("#135517"));
To set width and height of the layout,
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15, 5, 5, 5);
layout.setLayoutParams(params);
The orientation,
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setHorizontalGravity(Gravity.CENTER_HORIZONTAL);
layout.setPadding(10, 10, 5, 5);
Then create a textview,
TextView textView = new TextView(this);
textView.setLayoutParams(params);
textView.setPadding(2, 2, 2, 2);
textView.setText(" "your" ");
textView.setTextColor(getResources().getColor(R.color.white));
textView.setIncludeFontPadding(true);
Add the view to the parent,
layout.addView(textView);
I have a piece of code which I use to create a new LinearLayout. Within the layout I wish to add a TextView which contains both a label and a value. Then next to it on the right I want to display the button. I want the button to be located toward the end of the screen, without stretching the button. I am happy with the button width and height as WARP_CONTENT.
How can I achieve this in code? I have barely any XML so using XML is not an option. I am trying to make the app as dynamic as possible, so I decided to steer clear of XML.
Please see the code below:
// Build a button
final Button addButton = new Button(task.getParent());
addButton.setText("Add New");
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Open a file picker here to let the user pick a file
}
});
// Build a new layout to hold all the elements
LinearLayout verticalLayout = new LinearLayout(task.getParent());
verticalLayout.setOrientation(LinearLayout.HORIZONTAL);
verticalLayout.addView(sizeTextView);
verticalLayout.addView(addButton);
Thank you guys in advance.
Try this: Add Space (View) between TextView & Button.
// View space = new View(parent_context);
View space = new View(task.getParent());
// Width:0dp, Height:1 & Weight: 1.0
LinearLayout.LayoutParams spaceLP = new LinearLayout.LayoutParams(0, 1, 1.0f);
space.setLayoutParams(spaceLP);
verticalLayout.addView(sizeTextView);
verticalLayout.addView(space);
verticalLayout.addView(addButton);
Add textview with size and gravity,like this:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setLayoutDirection(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
verticalLayout.addView(sizeTextView,params);
To achieve this you should use Relative layout and RelativeLayout.LayoutParams. By using LayoutParams you can set the rule to align your views as per your requirements.
for example
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);
I have one main linear layout which contains dynamically generated linear layouts. I am animating these layouts on ACTION_DOWN. But if i try to change the margin (top or bottom) of one layout, it affects other layouts as well. How to change one layouts margin without affecting others.
Any help would be rally appreciated.
Thanks.
EDIT
public View getLinearView() {
ChildLinearLayout linearLayout = new ChildLinearLayout(context);
LayoutParams layoutParams = new LayoutParams(500, 500);
linearLayout.setLayoutParams(layoutParams);
linearLayout.setBackgroundColor(Color.RED);
layoutParams.setMargins(20, 20, 20, 20);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
TextView textView = new TextView(context);
textView.setText("Hello World");
linearLayout.addView(textView);
System.out.println("View Added");
views.add(linearLayout);
return linearLayout;
}
I think since you are calling
layoutParams.setMargins(20, 20, 20, 20)
for every dynamically generated layout, if you change these values then it will affect every one of your dynamically generated layouts.
Instead you could change your
getLinearView() method to getLinearView(int margin_value)
and every time you call this method for your dynamically generated layout, you could pass in the value you want for that particular layout.
ex:
If I have 5 layouts and I want to set margin of first one to 50 and others to 20 then
for(int i=0;i<5;i++)
{
if(i==0)
view=getLinearView(50);
else
view=getLinearView(20);
}
I can't make my EditTexts to fit in LinearLayout side by side sharing the same amout of space.
Here is the code that does it:
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textFieldsLayout = (LinearLayout) findViewById(R.id.LinearLayout2);
for(int i=1; i <= 8; i++){
final EditText ed = new EditText(this);
ed.setText("" + i);
ed.setInputType(2);
ed.setLayoutParams(lparams);
textFieldsLayout.addView(ed);
}
}
this code manages to add EditText to my layout but they appear side by side, and there is empty space at the end of LinearLayout, when I change params to WRAP_CONTENT, only first EditText added to layout fills the layout and others don't appear there, any idea what am I doing wrong here?
add layout_weight to the layout params
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f);
To make your views stretch to fill a LinearLayout you must make sure that the widths are set to 0 and the weights are set to 1.
This will give them an even split. It's basically telling the system to defer setting the width until its parent is measured. Then come up and let children fill in whatever space they have.
Need to set left margin to a button object programatically.
This is the code segment:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.for_button);
MarginLayoutParams ml = new MarginLayoutParams(-2,-2);
ml.setMargins(5, 0, 0, 0);
Button btn = new Button(this);
btn.setText("7");
btn.setTextColor(Color.WHITE);
btn.setBackgroundResource(R.drawable.date_button);
rl.addView(btn,ml)
I also tried
btn.setLayoutParams(ml);
rl.addView(btn);
Whats the big problem. Or is there any alternative way?
Alright, I'm gonna give this a shot IronBlossom; this is how I do it and I hope it works:
LinearLayout myLinearLayout = (LinearLayout)findViewById(R.id.my_linear_layout);
Button myButton = new Button(this);
// more myButton attribute setting here like text etc //
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(5,0,0,0);
myLinearLayout.addView(myButton, params);
best,
-serkan
You use a RelativeLayout as the parent for the button, but you don't specify any rules for the it where to place the button (e.g. ALIGN_PARENT_LEFT and ALIGN_PARENT_TOP).
You have to set rules for position when using a RelativeLayout though, so this messes with the layout calculation. This means that you have to use RelativeLayout.LayoutParams instead of the MarginLayoutParams because the former allows these rules and has proper default values set.
Alter this line:
MarginLayoutParams ml = new MarginLayoutParams(-2,-2);
to
RelativeLayout.LayoutParams ml = new RelativeLayout.LayoutParams(-2,-2);
Chances are that you also want to add rules because the default positioning values don't suit you (views get positioned in the top left corner of the parent layout by default). You can use RelativeLayout.LayoutParams.addRule() for that.