Change linear layout top margin programmatically android - android

i have two linear layouts in one frame layout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="left"
android:orientation="vertical">
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/image12">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="#+id/layoutbtnlinear_aboutme"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:gravity="bottom"
android:layout_marginTop="10dp"
android:background="#b2b2b2"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgShare_layout_aboutme"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_gravity="right|center|end"
android:layout_weight="1.63"
android:src="#drawable/ic_share" />
<TextView
android:id="#+id/txtTitle_layout_aboutme"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_gravity="left"
android:layout_weight="0.3"
android:fontFamily="Times New Roman"
android:text="About Me"
android:textColor="#android:color/black"
android:textSize="35sp"
android:textStyle="italic" />
</LinearLayout>
<LinearLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageButton
android:id="#+id/btnSlidingDrawerHandler_layout_aboutme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/ic_1_navigation_collapse" />
<ListView
android:id="#+id/listView_layout_aboutme"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:footerDividersEnabled="true"
android:dividerHeight="4px"
android:isScrollContainer="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbarStyle="outsideInset"
android:scrollbars="vertical">
</ListView>
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
Here I'm seting top margin of linear layout with id layoutbtnlinear_aboutme to 10dp but in code I want to change this 10dp to 50dp on some condition how can I change this top margin programatically?

layout = (LinearLayout) findViewById(R.id.layoutbtnlinear_aboutme);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)layout.getLayoutParams();
params.setMargins(0, 50, 0, 0);
layout.setLayoutParams(params);

LayaoutParams usually create confusion while setting margin because of their parent layout... So this MarginLayoutParams is very useful which works with all layouts.
Java Code
MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 200; //Ths value 200 is in px... Please convert in DP
params.leftMargin = 100;
params.topMargin = 200;
Kotlin code
val params: MarginLayoutParams = view!!.layoutParams as MarginLayoutParams
params.width = 200
params.leftMargin = 100
params.topMargin = 200

This updates the top margin without the need to update the other margin values.
LinearLayout layout = (LinearLayout) findViewById(R.id.your_linear_layout);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams();
layoutParams.topMargin = 200;
layout.setLayoutParams(layoutParams);

use this
layout = (LinearLayout) findViewById(R.id.layuout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
layout.setLayoutParams(layoutParams );

Use this method to set margin in dp
private 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();
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
// convert the DP into pixel
int l = (int)(left * scale + 0.5f);
int r = (int)(right * scale + 0.5f);
int t = (int)(top * scale + 0.5f);
int b = (int)(bottom * scale + 0.5f);
p.setMargins(l, t, r, b);
view.requestLayout();
}
}
Call the method :
setMargins(linearLayout,0,0,5,0);
https://stackoverflow.com/a/50951911/8523391

Kotlin solution:
fun LinearLayout.setMargins(left: Int? = null, top: Int? = null, right: Int? = null, bottom: Int? = null) {
val params: LinearLayout.LayoutParams = this.layoutParams as LinearLayout.LayoutParams
val left = left?.let { it } ?: params.leftMargin
val top = top?.let { it } ?: params.topMargin
val right = right?.let { it } ?: params.rightMargin
val bottom = bottom?.let { it } ?: params.bottomMargin
params.setMargins(left, top, right, bottom)
this.requestLayout()
}
then you just need to:
layoutbtnlinear_aboutme.setMargins(top = 10)

I have set up margins directly using below code (I tried using LinearLayout.LayoutParams but is was not working for me)
LinearLayout layout = (LinearLayout)findViewById(R.id.yourrelative_layout);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(3, 300, 3, 3);
layout.setLayoutParams(params);
Only this here is to notice that LayoutParams should be imported for following package android.widget.RelativeLayout.LayoutParams unless you will hit error.

Related

Create checkbox dynamically with weight attribute

I want to create checkboxes in java with for loop. i want to add it in gridlayout.
my problem is that checkbox take only wrap content size. I want that they should cover full width.
I can easily get it in xml like this.
<GridLayout
android:id="#+id/checkBoxLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:columnCount="2">
<CheckBox
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_columnWeight="1"
android:text="dfdfdffddfd"/>
<CheckBox
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_columnWeight="1"
android:text="dfdfdffddfd"/>
<CheckBox
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_columnWeight="1"
android:text="dfdfdffddfd"/>
</GridLayout>
but i want add these like this
<GridLayout
android:id="#+id/checkBoxLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:columnCount="2">
</GridLayout>
and Java code
for (int i = 0; i < 3; i++) {
CheckBox cb = new CheckBox(getActivity());
cb.setText("I'm dynamic!");
cb.setTextColor(Color.WHITE);
cb.setPadding(10, 10, 10, 10);
checkBoxLayout.addView(cb);
}
Something like:
final int h = 25;
final int w = 200;
final int margin = 10;
checkBoxLayout.setColumnCount(3);
checkBoxLayout.setRowCount(1);
for( i = 0 ; i < 3 ; i++ ) {
CheckBox check = new CheckBox( getActivity() );
check.setText("Checkout");
// check.setPadding(0, 0, 0, 0);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// left, top, right, bottom
params.setMargins(0, margin , 0, margin);
params.gravity = Gravity.NO_GRAVITY;
check.setLayoutParams(params);
check.setGravity(Gravity.CENTER);
checkBoxLayout.addView(check, w, h);
}

Creating multiple views

I am trying to inflate a view multiple times.
my view consists of one imageview and a textview below it and placing it at particular position.
Below is my item.xml which I am inflating multiple times:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="100dp"
android:background="#android:color/holo_blue_dark"
android:layout_height="100dp">
<ImageView
android:layout_gravity="center"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#mipmap/ic_launcher"
android:id="#+id/imageView"/>
<TextView
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="20dp"
android:textSize="12sp"
android:textStyle="bold"
android:text="Large Text"
android:id="#+id/textView" />
</LinearLayout>
Here is my code with inflate:
for (int i = 0; i < 1; i++) {
final View v = linf.inflate(R.layout.item, null);
TextView tvs = (TextView) v.findViewById(R.id.textView);
ImageView ivs = (ImageView) v.findViewById(R.id.imageView);
tvs.setText(i+"");
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
int w = (mWidth/2)-50;
int h =(mHeight/2)-50;
params.leftMargin = w;
params.topMargin = h;
Log.e("W-H", mWidth + "-" + mHeight);
rr.addView(v,params);
}
I am able to place the item.xml successfully but its not fitting screen properly I have set height and width fixed 100dp.
Here is what I am getting
here
The constructor for LayoutParams is in pixels, so you have to convert to dps for it to display correctly on your screen. This can be accomplished as in this stackoverflow answer:
int width_dps = 100;
int height_dps = 100;
final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
int width_pixels = (int) (width_dps * scale + 0.5f);
int height_pixels = (int) (height_dps * scale + 0.5f);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width_pixels, height_pixels);
Alternatively, if you are using a fixed size, you can update your xml to allow wrap_content to work correctly. You will be overriding the LinearLayout params, so you can update your subviews:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
and update a subview (android:layout_width="100dp"):
<TextView
android:gravity="center"
android:layout_width="100dp"
android:layout_height="20dp"
android:textSize="12sp"
android:textStyle="bold"
android:text="Large Text"
android:id="#+id/textView" />

Can't get the top of one ImageView to align to top of TextVIew

I have an ImageView and a TextView within a RelativeLayout that is nested inside a ScrollView. I can't get the Top of the ImageView to line up with the top of the TextView. It hovers about 150dp down from the top of the text view top edge.
Here is my xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/transitionForm"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/backgroundcolor"
android:orientation="horizontal" >
<ScrollView
android:id="#+id/svTutorial"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:splitMotionEvents="true"
android:layout_above="#+id/ImageBottom"
android:layout_below="#+id/ImageTop"
android:scrollbars="vertical"
>
<RelativeLayout
android:id="#+id/layoutTransitionPicWidgets"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/lblQuestionText"
android:layout_width="250dp"
android:layout_height="fill_parent"
android:layout_marginBottom="30px"
android:layout_marginLeft="50px"
android:layout_marginTop="10dp"
android:layout_marginRight="25px"
android:layout_alignParentLeft="true"
android:layout_weight="1"
android:text="get text from db."
android:textColor="#000000"
android:textSize="20sp" />
<ImageView
android:id="#+id/imgPic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/slidetest"
/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
I'm trying to programmatically change the width of the Image based on its size, so I am setting all the parameters programmatically.
Here is the code:
imgPic = (ImageView)findViewById(R.id.imgPic);
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
final float density = getResources().getDisplayMetrics().density;
final float dpHeight = outMetrics.heightPixels / density;
final float dpWidth = outMetrics.widthPixels / density;
ViewTreeObserver vto = imgPic.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
imgPic.getViewTreeObserver().removeOnPreDrawListener(this);
final int finalHeight = imgPic.getMeasuredHeight();
final int finalWidth = imgPic.getMeasuredWidth();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.width = Math.round(.4f * dpWidth * density);
params.leftMargin = 50;
params.topMargin = 0;
params.rightMargin = 25;
//params.gravity= Gravity.TOP;
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.RIGHT_OF, R.id.lblQuestionText);
imgPic.setLayoutParams(params);
return true;
}
});
I've tried doing this with a LinearLayout and get the same results. What am I missing?
You can add this to your ImageView
android:layout_alignTop="#+id/lblQuestionText"
but I think there's more going on than that. You don't specify any alignment attributes on the ImageView, so it may not layout where you think it's going to layout.
It seems like maybe you want the ImageView to be to the right of the TextView, in which case adding this to the ImageView should help:
android:layout_toRightOf="#+id/lblQuestionText"

BackgroundColor in LinearLayout of the width of the screen

I created a gallery with horizontalscrollview. In the imageview LinearLayout I've put a color background. I want the LinearLayout spans the width of the screen with or without images. How I can do?
<LinearLayout
android:id="#+id/linear1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="5dp"
android:orientation="vertical">
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none">
<LinearLayout
android:id="#+id/linear2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#color/estandar"
android:padding="2dp"
/>
</HorizontalScrollView>
</LinearLayout>
main.xml
LinearLayout linear2 = (LinearLayout) findViewById(R.id.linear2);
LayoutParams params = linear2 .getLayoutParams();
params.height = 100;
params.width = 300;
but my code does not work.
EDIT:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int anchoPantalla = metrics.widthPixels;
if (listaImagenes.length > 0) {
for (String nombreImagen : listaImagenes) {
InputStream is = getAssets().open(directorioImagenes + "/" + nombreImagen);
final Bitmap bitmap = BitmapFactory.decodeStream(is);
final ImageView imageView = new ImageView(getApplicationContext());
alto = bitmap.getHeight();
ancho = bitmap.getWidth();
final float calculo = ancho / (alto / ALTO_IMAGEN);
imageView.setLayoutParams(new ViewGroup.LayoutParams((int)calculo, ALTO_IMAGEN));
imageView.setImageBitmap(bitmap);
imageView.setPadding(2, 2, 2, 2);
imageView.setBackgroundColor(colorResources);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
...
}
});
linear2.addView(imageView);
}
} else {
// PAINT LINE WIDTHSCREEN x 120dp
}
LinearLayout galeria2 = (LinearLayout) findViewById(R.id.linear2);
LayoutParams params = galeria2.getLayoutParams();
params.height = 100;
params.width = 300;
galeria2.setLayoutParams(params);
You have to dynamically add width to each element of HorizontalScrollView. I have modified your code have a look. Its working fine.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="5dp"
android:orientation="vertical">
<HorizontalScrollView
android:id="#+id/hsv"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:scrollbars="none">
<LinearLayout
android:id="#+id/linear2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#FF0040"
android:padding="2dp"
/>
</HorizontalScrollView>
Now in code add element like (see the highlited line)
LinearLayout galeria2 = (LinearLayout) findViewById(R.id.linear2);
ImageView iv1 = new ImageView(this);
iv1.setImageResource(R.drawable.ic_launcher);
**iv1.setLayoutParams(new LinearLayout.LayoutParams(
720, LayoutParams.MATCH_PARENT));**
ImageView iv2 = new ImageView(this);
**iv2.setLayoutParams(new LinearLayout.LayoutParams(
720, LayoutParams.MATCH_PARENT));**
galeria2.addView(iv1);
galeria2.addView(iv2);

Set TextView width to 0dp doesn't work

How to set programmatically width of TextView to be 0dp ? I am trying to put in LinearLayout couple TextViews but all to be same width, and when I put in xml like
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="left"
android:gravity="left"
/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
/>
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="test"
android:layout_gravity="right"
android:gravity="right"
/>
</LinearLayout>
but when in code try like
TextView txtTemp = new TextView(this);
txtTemp.setText(captures.get(i));
LinearLayout.LayoutParams tempLL = (LinearLayout.LayoutParams) txtTemp
.getLayoutParams();
tempLL.width =0;
tempLL.height = LinearLayout.LayoutParams.WRAP_CONTENT;
tempLL.weight = 1;
if (i == 0) {
tempLL.gravity = Gravity.LEFT;
}
if (i == (captures.size() - 1)) {
tempLL.gravity = Gravity.RIGHT;
} else {
tempLL.gravity = Gravity.CENTER;
}
txtTemp.setLayoutParams(tempLL);
I got exception on tempLL.width null exception. How to solve this ?
Instead of using
LinearLayout.LayoutParams tempLL = (LinearLayout.LayoutParams) txtTemp
.getLayoutParams();
tempLL.width =0;
tempLL.height = LinearLayout.LayoutParams.WRAP_CONTENT;
tempLL.weight = 1;
try this
LinearLayout.LayoutParams tempLL = new LinearLayout.LayoutParams(0,
LayoutParams.WRAP_CONTENT,1.0);
txtTemp.setLayoutParams(tempLL);
You are creating a new textview and there is no layoutparams specified yet. So getLayoutParams should return null. So create a new layoutparam object and set that to the new textview.

Categories

Resources