How to setMargins in LinearLayout in Java? - java

I'm trying to use the setMargins method using ViewGroup but I keep getting the error that setMargins is not defined .This is my code:
LinearLayout content = new LinearLayout(activity);
LayoutParams params = content.getLayoutParams();
params.setMargins(0, 0, 0, 40);
content.setLayoutParams(params);

You should use LayoutParams to set your button margins:
LayoutParams params = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
yourbutton.setLayoutParams(params);
Depending on what layout you're using you should use RelativeLayout.LayoutParams or LinearLayout.LayoutParams.
And to convert your dp measure to pixel, try this:
Resources r = mContext.getResources();
int px = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
yourdpmeasure,
r.getDisplayMetrics()
);

Use this method to setMargins depend on any view (LinearLayout, RelativeLayout etc.)
Pass the params in integer format
public static void setMargins(View view, int left, int top, int right, int bottom) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
p.setMargins(left, top, right, bottom);
view.requestLayout();
}
}

Related

Add Space between LinearLayouts

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:

How to add bottom padding to span content of textView within RelativeLayout programmatically

How can padding be added to the bottom of the textview programmatically? I noticed that there is some padding above the text but not below. What can be done in order to add some black padding at the bottom just like at the top? It would make the text view a lot more legible (especially for letters that extend below the baseline i.e. g and y).
TextView tv1 = v.findViewById(R.id.textView1);
String myString = " " + getString(R.string.magnify) + " ";
Spannable spanna = new SpannableString(myString);
spanna.setSpan(new BackgroundColorSpan(Color.BLACK), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanna.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.yellow)), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv2.setText(spanna);
With this custom ReplacementSpan, text is drawn "vertically center"
final SpannableString spannableString = new SpannableString(myString);
stringBuilder.append(spannableString);
stringBuilder.setSpan(new TagSpan(Color.BLACK, Color.MAGENTA), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
testTextView.setText(stringBuilder, TextView.BufferType.SPANNABLE);
Class TagSpan
public class TagSpan extends ReplacementSpan {
private RectF mRect;
private int mBackgroundColor;
private int mForegroundColor;
public TagSpan(int backgroundColor, int foregroundColor) {
this.mRect = new RectF();
this.mBackgroundColor = backgroundColor;
this.mForegroundColor = foregroundColor;
}
#Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
// Background
mRect.set(x, top, x + paint.measureText(text, start, end), bottom);
paint.setColor(mBackgroundColor);
canvas.drawRect(mRect, paint);
// Text
paint.setColor(mForegroundColor);
int xPos = Math.round(x);
int yPos = (int) (0 + ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)));
canvas.drawText(text, start, end, xPos, yPos, paint);
}
#Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return Math.round(paint.measureText(text, start, end));
}
}
Not exactly answer to "bottom padding" request but solve part of your problem I think.
(Original post)
You can use: yourTextView.setPadding(0, 10, 0, 0); Android - How to set padding for TextView in ListView or ExpandableListView
Or increase the TextviewHeight and centre the text.
Set RelativeLayout.LayoutParams for Textview
TextView tv1 = v.findViewById(R.id.textView1);
String myString = " " + getString(R.string.magnify) + " ";
Spannable spanna = new SpannableString(myString);
spanna.setSpan(new BackgroundColorSpan(Color.BLACK), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spanna.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.yellow)), 0, myString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv1.setText(spanna);
RelativeLayout.LayoutParams params= new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, tv1.getId());
tv1.setLayoutParams(params);

Adding second TextView replaces the first TextView in a LinearLayout

I am adding TextViews programatically to a LinearLayout. But when the second TextView is added, it seems to replace the first.
Here is the code:
LinearLayout l = (LinearLayout) findViewById(R.id.contacts_container);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
String username = object.getString("username");
String status = object.getString("status");
// create wrapper
LinearLayout wrapper = new LinearLayout(getApplicationContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
wrapper.setOrientation(LinearLayout.HORIZONTAL);
int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
wrapper.setPadding(padding,padding,padding,padding);
wrapper.setLayoutParams(lp);
l.addView(wrapper);
// add Imageview to wrapper
ImageView image = new ImageView(getApplicationContext());
image.setBackgroundResource(R.drawable.icon_only_dark_crop);
lp = new LinearLayout.LayoutParams((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()), (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics()));
lp.setMargins(0, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()), 0);
image.setLayoutParams(lp);
wrapper.addView(image);
// add linearLayout text wrapper to main wrapper
LinearLayout textWrapper = new LinearLayout(getApplicationContext());
textWrapper.setOrientation(LinearLayout.VERTICAL);
textWrapper.setPadding(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()), 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 0.9f);
textWrapper.setLayoutParams(params);
wrapper.addView(textWrapper);
// add username TextView to textWrapper
TextView usernameText = new TextView(getApplicationContext());
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
usernameText.setLayoutParams(lp);
usernameText.setText(username);
usernameText.setTextColor(Color.parseColor("#FFFFFF"));
usernameText.setTextSize(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
textWrapper.addView(usernameText);
// add status TextView to textWrapper
TextView statusText = new TextView(getApplicationContext());
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
usernameText.setLayoutParams(lp);
usernameText.setText(status);
usernameText.setTextColor(Color.parseColor("#FFFFFF"));
usernameText.setTextSize(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
textWrapper.addView(statusText);
}
It loops twice and two "wrapper" LinearLayouts get added to the main LinearLayout fine. But for each wrapper LinearLayout it should add two TextViews, but when I run the application, only the statusView displays. If I remove the statusView, the usernameView displays fine.
Why is that when the statusView is added to the wrapper, the usernameView seems to be hidden or removed?
You copy pasted the same layout variable name when initializing the second textview
use this instead
// add username TextView to textWrapper
TextView usernameText = new TextView(getApplicationContext());
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
usernameText.setLayoutParams(lp);
usernameText.setText(username);
usernameText.setTextColor(Color.parseColor("#FFFFFF"));
usernameText.setTextSize(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
textWrapper.addView(usernameText);`
// add status TextView to textWrapper
TextView statusText = new TextView(getApplicationContext());
lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
statusText.setLayoutParams(lp);
statusText.setText(status);
statusText.setTextColor(Color.parseColor("#FFFFFF"));
statusText.setTextSize(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
textWrapper.addView(statusText);
in your second textview, check the below text.
TextView **statusText** = new TextView(getApplicationContext());
**usernameText**.setLayoutParams(lp);
**usernameText**.setText(status);
**usernameText**.setTextColor(Color.parseColor("#FFFFFF"));
**usernameText**.setTextSize(0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
textWrapper.addView(statusText);
Probably because your textWrapper does'nt have a orientation specified. Define it as vertical or horizontal depending on your needs and it should work fine.

On Android: How to calculate row height prior to TextView creation?

Can anyone explain correlation between Paint.setTextSize() and TextView.setTextSize() ?
I have code like this:
Rect bounds = new Rect();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(48);
paint.getTextBounds("W", 0, 1, bounds);
int rowHeight = bounds.height();
LayoutParams params1 = new RelativeLayout.LayoutParams(300, rowHeight);
TextView tv = new TextView(getContext());
tv.setLayoutParams(params1);
**tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 48);**
but final text size in TextView is way bigger than rowHeight calculated.
I guess, my question is:
Is there any way to calculate rowHeight prior to TextView creation so that text fits by HEIGHT not width?
Thanks

Android: Changing ImageView size is not working

I am trying to change my ImageView size, but I can't seem to change both - width and height. If I just change one of them, then all works correctly, but when I try to change both, only width is changed.
I have the size in dp: width 22 and height 38, and I convert them to px. Is there another way to do so? I have tried many other ways, but they don't seem to work either.
Could someone tell me, what I should do differently?
Here is my code:
public GridLayout gridLayout;
public GridLayout.Spec row = GridLayout.spec(0);
public GridLayout.Spec col = GridLayout.spec(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridLayout = (GridLayout) findViewById(R.id.gameGrid);
createBlock();
}
public void createBlock() {
ImageView block = new ImageView(this);
block.setImageResource(R.drawable.red);
if (gridLayout != null) {
gridLayout.addView(block, new GridLayout.LayoutParams(row, col));
int width_in_dp = 22, height_in_dp = 38;
final float scale = getResources().getDisplayMetrics().density;
int width_in_px = (int) (width_in_dp * scale + 0.5f);
int height_in_px = (int) (height_in_dp * scale + 0.5f);
ViewGroup.LayoutParams layoutParams = block.getLayoutParams();
layoutParams.width = width_in_px;
layoutParams.height = height_in_px;
block.setLayoutParams(layoutParams);
}
}
Have you tried playing with the block's scaleType? The default is fitCenter but I usually choose centerCrop or fitXY. Here's a good webpage that describes the differences.
You can set the scaleType through ImageView's setScaleType method.

Categories

Resources