I want to set the width and height of a RelativeLayout
to a fixed value. My item_view.xml
looks like this;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:orientation="vertical"
android:background="#00ff00">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="abc"/>
</RelativeLayout>
Here is the activity_main.xml
:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
And finally my generateView function in the MainActivity.java
;
private void generateItemView()
{
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = layoutInflater.inflate(R.layout.item_view, null);
RelativeLayout containerView = findViewById(R.id.container);
containerView.addView(itemView);
}
And this is the result;
As you can see, this is not 100dpX100dp size.
On the other hand, if I do this programmatically it works. Here is the updated generateView function;
private void generateItemView()
{
LayoutInflater layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = layoutInflater.inflate(R.layout.item_view, null);
int sizeDp = 100;
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int sizePx = Math.round(sizeDp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(sizePx, sizePx);
itemView.setLayoutParams(params);
RelativeLayout containerView = findViewById(R.id.container);
containerView.addView(itemView);
}
And it works just fine...
My question is, why can't we use the layout_width and layout_height properties in the layout xml file?