on xml layout, I have a FrameLayout with no child. Then I add a list buttons programatically into this framelayout by this code below:
private void addNumbers(){ // Numbers is set with random position
for (int i = 1; i < 20; i++) {
Button btn = new Button(this);
btn.setText("" + i);
btn.setId(i);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(50, 50);
int leftMargin = new Random().nextInt(widthScreen - btnSize );
int topMargin = new Random().nextInt(heightScreen - btnSize);
lp.leftMargin = leftMargin;
lp.topMargin = topMargin;
btn.setLayoutParams(lp);
framelayout1.addView(btn);
//framelayout2.addView(btn);
}
}
And some buttons overlap together, I do not want to happen this. How to avoid this problem ? Thanks in advance.
P/s: Sorry I can not upload image from my company, all upload > 4K is reject, please tell me if the question is not clear.
Related
This is my code:
ConstraintLayout.LayoutParams buttonParams = new ConstraintLayout.LayoutParams(40,105);
buttonParams.setMargins(8,16,24,32);
secretCodeFields = findViewById(R.id.secretCodeFields);
for (int i = 0; i < 4; i++) {
Button b = new Button(this);
vID[i]=View.generateViewId();
b.setId(vID[i]);
b.setLayoutParams(buttonParams);
secretCodeFields.addView(b);
}
set.clone(secretCodeFields);
set.createHorizontalChain(
secretCodeFields.getId(),ConstraintSet.LEFT,
secretCodeFields.getId(),ConstraintSet.RIGHT,
vID,null,ConstraintSet.CHAIN_PACKED
);
set.applyTo(secretCodeFields);
Buttons are added in the same place (so only last one is visible). The same resultat if I delete "b.setLayoutParams(buttonParams);" line and use
secretCodeFields.addView(b,buttonParams);
But if I add button with width and height params it works, but there are no more margins:
secretCodeFields.addView(b,90,90);
What I do wrong?
EDIT:
secretCodeFields is ConstraintLayout
I found solution. I added margins AFTER set.applyTo... :
for (int i = 0; i < codeLenght; i++) {
Button b = (Button)findViewById(vID[i]);
ConstraintLayout.LayoutParams p = (ConstraintLayout.LayoutParams) b.getLayoutParams();
p.setMargins(6,0,6,0);
b.setLayoutParams(p);
}
It works, but I don't know if it is the best solution.
I know this is a late answer but here it is
the ConstraintSet.CHAIN_PACKED will remove all applied margins to your views
you should first create the chain in Constraint Set then after that apply margins using the ConstrainSet connect(int startID, int startSide, int endID, int endSide, int margin) method to indicate margins.
I'm trying to make a list of database items like the following..
for (int i=0; i < jArray.length(); i++)
{
JSONObject row = jArray.getJSONObject(i);
LinearLayout ll = new LinearLayout(MainActivity.this);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,100));
Button btn = new Button(MainActivity.this);
//btn.setText(row.getString("subject"));
btn.setText(String.valueOf(i));
btn.setLayoutParams(new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT,(float)0.8));
File imgFile = new File(file_path);
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView iv = new ImageView(MainActivity.this);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setImageBitmap(myBitmap);
iv.setLayoutParams(new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT,(float)0.2));
ll.addView(btn);
ll.addView(iv);
LinearLayout sv = findViewById(R.id.sv_layout);
sv.addView(ll);
}
The result is like this:
But I want to have space between Linear Layouts and make Image height shorter to be equal with button height
How can I achieve this? Thank you,
Please Try this code
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 100);
params.setMargins(0, 5, 5, 10);
ll.setLayoutParams(params);
you can add your specific margins in this line params.setMargins(0, 5, 5, 10);
Take button and image in linear layout with horizontal orientation. Set Button and Imageview height to wrap content. Now for gap between Linear Layouts give appropriate margin.
Set the margins in the layout params and pass them to your ImageView object.
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT,(float)0.2);
int dp = getDps(8);
layoutParams.setMargins(0,dp,0,dp);
iv.setLayoutParams(layoutParams);
Function getDps():
public int getDps(int sizeInDp){
float scale = getResources().getDisplayMetrics().density;
return (int) (sizeInDp*scale + 0.5f);
}
This looks like:
I'm trying to create a number of edit texts programmatically without using XML, but I faced some problems while trying this out. Here is a piece of code:
private void createEditText(int l, int topMargin){
ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) editText.getLayoutParams();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(vlp.width, vlp.height);
layoutParams.setMargins((vlp.leftMargin + l) - vlp.width - vlp.height - 25, topMargin, vlp.rightMargin, vlp.bottomMargin);
final EditText newEditText = new EditText(this);
newEditText.setBackgroundResource(R.drawable.rounded_edittext);
newEditText.setLayoutParams(layoutParams);
linearLayout.addView(newEditText);
}
private void numberOfEditTexts(){
String[] words = Answers.answers[getCurrentLevel()].split(" ");
int l = 0, topMargin = 450;
for(int i = 0; i < words.length - 1; i++){
createEditText(l, topMargin);
l += editText.getLayoutParams().width + 5;
if(i == 0) topMargin -= 560;
}
}
The first function creates an edit text and I send 2 parameteres to it, of which the topMargin is the variable that defines the altitude coordinates of the edit text. So the problem is that this edit text will appear differently on different devices because of their screen sizes.
How can I fix it? How can I avoid setting the position manually?
Thanks in advance.
I think you need to get the screen width and length. Use the percentage of screen size as your margin size.
to get the screen size by pixels,
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Your margin can be some percentage of the height: like 5% or 10% of the screen height. Then it is adjustable.
How can I get the border width of a stand Android button programmatically? I simply need to resize the text to fit to the gray area and need to position other objects inline with the buttons, but I cannot do that without knowing the size of the border. I need this to work in all API's 7+. The red arrows in the image below show what I am trying to get:
Here is the code I use for creating my button:
cmdView = new Button(this);
params = new RelativeLayout.LayoutParams(widthLblViewVerbs , (int) fieldHeight);
params.leftMargin = (int) (screenWidth - params.width);
params.topMargin = (int) yPos;
cmdView.setSingleLine();
cmdView.setText("View");
cmdView.setPadding(0, 0, 0, 0);
cmdView.setTextSize(TypedValue.COMPLEX_UNIT_PX, SetTextSize(cmdView.getText().toString(), params.width, params.height));
layout.addView(cmdView, params);
NB. I've had to ask this question again because someone downvoted my question last time and I am desperate for a solution. I have made absolutely no progress with my program in weeks because I have been stuck with this and another problem. If there is something unclear about my question, please let me know and I will edit it. Thank you
My initial code recommendation from the comments can be found here. The implementation done by Dan Bray is:
final Button button = new Button(this);
params = new RelativeLayout.LayoutParams(50, 50);
layout.addView(button, params);
button.post(new Runnable()
{
#Override
public void run()
{
button.buildDrawingCache();
Bitmap viewCopy = button.getDrawingCache();
boolean stillBorder = true;
PaddingLeft = 0;
PaddingTop = 0;
while (stillBorder)
{
int color = viewCopy.getPixel(PaddingLeft, button.getHeight() / 2);
if (color != Color.TRANSPARENT)
stillBorder = false;
else
PaddingLeft++;
}
stillBorder = true;
while (stillBorder)
{
int color = viewCopy.getPixel(button.getWidth() / 2, PaddingTop);
if (color != Color.TRANSPARENT)
stillBorder = false;
else
PaddingTop++;
}
}
});
Not really clear on the question - you want the margins of the underlying view and then the set the size of the button to match ? Then Have you tried
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
margins are accessible via
lp.leftMargin;
lp.rightMargin;
lp.topMargin;
lp.bottomMargin;
Details here:http://developer.android.com/reference/android/view/ViewGroup.MarginLayoutParams.html
This gets the width and height of the button's border:
final Button button = new Button(this);
params = new RelativeLayout.LayoutParams(50, 50);
layout.addView(button, params);
button.post(new Runnable()
{
#Override
public void run()
{
button.buildDrawingCache();
Bitmap viewCopy = button.getDrawingCache();
boolean stillBorder = true;
PaddingLeft = 0;
PaddingTop = 0;
while (stillBorder)
{
int color = viewCopy.getPixel(PaddingLeft, button.getHeight() / 2);
if (color != Color.TRANSPARENT)
stillBorder = false;
else
PaddingLeft++;
}
stillBorder = true;
while (stillBorder)
{
int color = viewCopy.getPixel(button.getWidth() / 2, PaddingTop);
if (color != Color.TRANSPARENT)
stillBorder = false;
else
PaddingTop++;
}
}
});
Assuming you are using a nine patch background image, there is a much easier way.
In the nine patch image, you can define a padding box. This padding box will automatically be applied to the contents you set. No need to recalculate the paddings manually in that case.
Note that you should not set a padding on views using a nine patch as a background as the padding from the nine patch will be ignored.
I want to set margin of Imageview. What I wanted to achieve is to move one image up to some distance. The content of screen is RelativeLayout, in that there is ImageView at left and button at right aligned. Now I want to move image from left to right within the gap between Image and Button in 100 click of button. The code I am following is as below:
private static int count= 1 ;
public void onClick(View view) {
RelativeLayout lay = (RelativeLayout)findViewById(R.id.layout1);
ImageView i1= (ImageView)findViewById(R.id.img1);
ImageButton btn= (ImageButton)findViewById(R.id.iBtn);
int i1Width = i1.getWidth();
int btnWidth = btn.getWidth();
int totalMragine = lay.getWidth() - i1Width - btnWidth ; //the total margine image will move.
int stepSize = (lay.getWidth() - i1Width - btnWidth ) / 100;
int step = stepSize * count++;
Log.i("i1Width ", ""+i1Width );
Log.i("btnWidth ", ""+btnWidth );
Log.i("lay.getWidth()", ""+lay.getWidth());
Log.i("stepSize", ""+stepSize);
Log.i("count", ""+count);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(step, 0, 0, 0);
i1.setLayoutParams(lp);
LinearLayout.LayoutParams lp1 = (LinearLayout.LayoutParams) horse.getLayoutParams();
Log.i("currentMargine", ""+lp1.leftMargin);
if(lp1.leftMargin >= totalMragine ){
Log.i("Result", "maringe over");
}
}
What I wanted to know that the margin I am setting is in Integer but the value for the step is in float. So How to set margin float in LayoutParams? or is there any other way to do this?
you can do one thing calculate distance to move every time as when going to move
distance to move = the rest of length/rest of clicks
of in final step (100th step) it will reach to end with error < . 5px and . 5px is too small )
like in
1st click distance_to_move = 370/100; as round off come 4
2nd click distance_to_move = 366/99; as round off come 4
3rd click distance_to_move = 362/98; as round off come 4
so movemnt will be as in px 44444...3444...3444..3444...