Here I am adding a textview inside a linearlayout programatically inside another linearlayout. However, I can't apply margin to my linearlayout even though I set it.
LinearLayout LL = new LinearLayout(TimeTableAdvanced.this);
LL.setBackgroundColor(getResources().getColor(R.color.menublue));
LL.setOrientation(LinearLayout.VERTICAL);
LL.setGravity(Gravity.TOP);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
int marginPixel = 3;
float density = TimeTableAdvanced.this.getResources().getDisplayMetrics().density;
int marginDp = (int)(marginPixel * density);
int marginTopPixel = 3;
int marginTopDp = (int)(marginTopPixel * density);
LLParams.setMargins(marginDp, marginTopDp, marginDp, marginDp);
LL.setLayoutParams(LLParams);
int paddingPixel = 3;
int paddingDp = (int)(paddingPixel * density);
LL.setPadding(paddingDp,paddingDp,paddingDp,paddingDp);
TextView infoheader = new TextView(TimeTableAdvanced.this);
infoheader.setText(getResources().getString(R.string.departuretimesfromfirstbusstop));
infoheader.setTextColor(getResources().getColor(R.color.white));
infoheader.setTextSize(14.0f);
LLParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
marginPixel = 5;
marginDp = (int)(marginPixel * density);
LLParams.setMargins(marginDp, 0, 0, 0);
infoheader.setLayoutParams(LLParams);
LL.addView(infoheader);
timetablelayout.addView(LL);
Try this, hope it will work.
LinearLayout.LayoutParams LLParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
LLParams.setMargins(marginDp, marginTopDp, marginDp, marginDp);
P.S
Just suggesting method to convert dp to pixels, have a try :)
private int dpToPx(int dp) {
float density = getResources().getDisplayMetrics().density;
return Math.round((float) dp * density);
}
Related
I have successfully added a new view to the bottom of my layout using the resources on Stack Exchange and other. However, if I try to add a second view programmatically, the two views appear to overlap.
This code block successfully adds a new view to my layout file.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
// First view
View playControlsPanelMinimized = new View(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
final float scale = activityMain.getContext().getResources().getDisplayMetrics().density;
float dps = 10;
int pixels = (int) (dps * scale + 0.5f);
params.height = pixels;
playControlsPanelMinimized.setLayoutParams(params);
playControlsPanelMinimized.setBackgroundColor(Color.parseColor("#00FFFF"));
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
activityMain.addView(playControlsPanelMinimized);
However, when I add a second view by simply repeating the code with new variables, I see there is an overlap behavior, to the effect that I only see the first view.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout activityMain = (RelativeLayout)findViewById(R.id.activity_main);
// First view
View playControlsPanelMinimized = new View(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
final float scale = activityMain.getContext().getResources().getDisplayMetrics().density;
float dps = 10;
int pixels = (int) (dps * scale + 0.5f);
params.height = pixels;
playControlsPanelMinimized.setLayoutParams(params);
playControlsPanelMinimized.setBackgroundColor(Color.parseColor("#00FFFF"));
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
activityMain.addView(playControlsPanelMinimized);
// Second View
View playControlsPanelMinimized2 = new View(this);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
final float scale2 = activityMain.getContext().getResources().getDisplayMetrics().density;
float dps2 = 10;
int pixels2 = (int) (dps2 * scale2 + 0.5f);
params2.height = pixels2;
playControlsPanelMinimized2.setLayoutParams(params2);
playControlsPanelMinimized2.setBackgroundColor(Color.parseColor("#00FFFF"));
params2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
activityMain.addView(playControlsPanelMinimized2);
edit:
I changed activity_main.xml to LinearLaout, and adjusted my variables accordingly, but now I no longer see the views.
LinearLayout activityMain = (LinearLayout)findViewById(R.id.activity_main);
// First View
View playControlsPanelMinimized = new View(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
final float scale = activityMain.getContext().getResources().getDisplayMetrics().density;
float dps = 10;
int pixels = (int) (dps * scale + 0.5f);
params.height = pixels;
playControlsPanelMinimized.setLayoutParams(params);
playControlsPanelMinimized.setBackgroundColor(Color.parseColor("#00FFFF"));
//params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
activityMain.addView(playControlsPanelMinimized);
edit
I am trying a new technique with the relative layout method to no avail as of yet
View playControlsPanelMinimized = new LinearLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
final float scale = activityMain.getContext().getResources().getDisplayMetrics().density;
float dps = 10;
int pixels = (int) (dps * scale + 0.5f);
params.height = pixels;
playControlsPanelMinimized.setLayoutParams(params);
playControlsPanelMinimized.setBackgroundColor(Color.parseColor("#00FFFF"));
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
activityMain.addView(playControlsPanelMinimized);
View A = new View(this);
View B = new View(this);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
A.setLayoutParams(params2);
B.setLayoutParams(params2);
playControlsPanelMinimized.addView(A);
playControlsPanelMinimized.addView(B);
Replace your RelativeLayout activity_main with LinearLayout which have orientation horizontal or vertical
Use lnearLayout instead of Relative layout, may be you need to use weightsum
set orientation to vertical / horizontal
put view right of other view and set it in xml .
i want ImageView's to look same on different screen sizes. To make it easier for you to understand how it should look there are some image:
Biggest problem is that my imageViews are created programmatically. ImageViews layout and size are set by this code
LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = 650;
ImageViewas.getLayoutParams().width = 950;
params.setMargins(0, 50, 0, 0);
Any ideas how to change this code that my app can look same on diffrent screen sizes?
Well, you can retrieve device resolution and set imageView width and height. Here is the solution.
private class ScreenResolution {
int width;
int height;
public ScreenResolution(int width, int height) {
this.width = width;
this.height = height;
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
ScreenResolution deviceDimensions() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// getsize() is available from API 13
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2) {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return new ScreenResolution(size.x, size.y);
}
else {
Display display = getWindowManager().getDefaultDisplay();
// getWidth() & getHeight() are deprecated
return new ScreenResolution(display.getWidth(), display.getHeight());
}
}
..................
LinearLayout LinearLayoutas = (LinearLayout)findViewById(R.id.LinearLayout);
ImageView ImageViewas = new ImageView(this);
ImageViewas.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayoutas.setGravity(Gravity.CENTER);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ScreenResolution screenRes = deviceDimensions();
ImageViewas.setLayoutParams(params);
ImageViewas.getLayoutParams().height = screenRes.height;
ImageViewas.getLayoutParams().width = screenRes.width;
params.setMargins(0, 50, 0, 0);
Also when the device orientation will be changed, the width and height should be swapped. You can do that in onConfigurationChanged:
#Override
public void onConfigurationChanged(Configuration newConfiguration) {
super.onConfigurationChanged(newConfiguration);
// swap device width and height here and re-assign
}
I'm playing around in Android and what I'm trying to achieve is a 10x10tile boardgame.
I want to read size and width of screen and then I want a square in the middle with a textViews above and below.
This is what I've done so far:
public void init(){
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
screenWidth = size.x;
screenHeight = size.y;
}else{
Display d = w.getDefaultDisplay();
screenWidth = d.getWidth();
screenHeight = d.getHeight();
}
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.LinearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView TVtop = new TextView(this.getApplicationContext());
TVtop.setHeight((screenHeight-screenWidth)/2);
TVtop.setWidth(screenWidth);
TVtop.setText("TOP");
TextView TVbot = new TextView(this.getApplicationContext());
TVbot.setHeight((screenHeight-screenWidth)/2);
TVbot.setWidth(screenWidth);
TVbot.setText("BOT");
TableLayout tableLayout = new TableLayout(this.getApplicationContext());
//Make a cube
LayoutParams tableParams = new LayoutParams(screenWidth, screenWidth);
tableLayout.setLayoutParams(tableParams);
//Populate tableLayout
for(int i = 0; i < nrOfTiles; i++){
TableRow tableRow = new TableRow(this.getApplicationContext());
for(int j = 0; j < nrOfTiles; j++){
ImageView imgView = new ImageView(this.getApplicationContext());
imgView.setImageResource(R.drawable.cell);
tableRow.addView(imgView);
}
tableLayout.addView(tableRow);
}
linearLayout.addView(TVtop);
linearLayout.addView(tableLayout);
linearLayout.addView(TVbot);
}
}
I've tried diffrent layoutparams but nothing seems to get the work done. :S
BR
Personally, I would use a RelativeLayout and setMargins for the items.
While not a direct answer to your question, the following code will display 15 icons in three rows. This should be enough to explain and get you started.
The main activity.
public class MainActivity extends Activity {
private int mWidth;
private int mTile;
private int mColMax = 5;
private Context mContext;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
// the screen width is need to work out the tile size
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Point size = new Point();
w.getDefaultDisplay().getSize(size);
mWidth = size.x;
}else{
mWidth = w.getDefaultDisplay().getWidth();
}
// how wide (and high) each icon will be to fit the screen.
mTile = (mWidth / mColMax);
setContentView(R.layout.activity_main);
// layout the icons
initUI();
}
/**
* Layout 15 icon images in three rows dynamically.
*/
private void initUI() {
// this is the layout from the XML
ViewGroup layout = (ViewGroup) findViewById(R.id.main_layout);
ImageView iv;
RelativeLayout.LayoutParams params;
int i = 0;
int row = 0;
int col = 0;
do {
params = new RelativeLayout.LayoutParams(mTile,mTile);
params.setMargins((col * mTile), (row * mTile), 0, 0);
iv = new ImageView(mContext);
iv.setAdjustViewBounds(true);
iv.setScaleType(ScaleType.FIT_CENTER);
iv.setImageResource(R.drawable.ic_launcher);
iv.setLayoutParams(params);
layout.addView(iv);
if (col == mColMax) {
row++;
col = 0;
} else {
col++;
}
} while (++i <= 16);
}
}
And the layout XML.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
using a dialog as a window I tried to set its layout as
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.x = 120;
lp.y = 120;
lp.width = 800;
lp.height = 450;
Dialog dialog = new Dialog(cxt);
dialog.getWindow().setAttributes(lp);
dialog.setContentView(vFirst);
dialog.show();
where
View vFirst = inflater.inflate(R.layout.popup, container, false);
which is inside a button click,but it is not setting it.
I think you should use this
dialog.getWindow().setLayout(800, 450);
This will set the dialog window size.
public class Myclass extends Dialog
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutParams params = getWindow().getAttributes();
params.height = LayoutParams.FILL_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
}
}
layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="#+id/dialogWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
// contents here
</LinearLayout>
According to documentation: http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html,
X position for this window. With the default gravity it is ignored. When using LEFT or START or RIGHT or END it provides an offset from the given edge.
Y position for this window. With the default gravity it is ignored. When using TOP or BOTTOM it provides an offset from the given edge.
So to make x and y work you should set Gravity attribute before. For example:
lp.gravity = Gravity.TOP;
lp.gravity = Gravity.LEFT;
lp.y = 120;
lp.x = 120;
//dialog width and height are set according to screen, you can take you want
Dialog myDialog = new Dialog(context, R.style.CustomTheme);
myDialog.setContentView(R.layout.share_post_dialog);
int[] widthHeight = getDeviceWidthAndHeight(context);
int dialogHeight = widthHeight[1] - widthHeight[1] / 4;
int dialogWidth = widthHeight[0] - widthHeight[0] / 5;
WindowManager.LayoutParams params = myDialog.getWindow().getAttributes();
params.width= dialogWidth;
params.height = dialogHeight;
myDialog.getWindow().setAttributes((WindowManager.LayoutParams) params);
myDialog.show();
//This is used to get height width of screen
#SuppressWarnings("deprecation")
public static int[] getDeviceWidthAndHeight(Context context) {
int widthHeght[] = new int[2];
int measuredWidth = 0;
int measuredHeight = 0;
WindowManager w = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
Point size = new Point();
w.getDefaultDisplay().getSize(size);
measuredWidth = size.x;
measuredHeight = size.y;
widthHeght[0] = measuredWidth;
widthHeght[1] = measuredHeight;
} else {
Display d = w.getDefaultDisplay();
measuredWidth = d.getWidth();
measuredHeight = d.getHeight();
widthHeght[0] = measuredWidth;
widthHeght[1] = measuredHeight;
}
return widthHeght;
}
I want to manage the height and width of an EditText box programmatically in Android. I tried edittext.setWidth(32); and edittext.setEms(50);, but both are not working. See my below code, as I am using it to create dynamic EditTexts in Android.
private EditText createEditText()
{
final LayoutParams lparams = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
final EditText edittext = new EditText(this);
edittext.setLayoutParams(lparams);
edittext.setWidth(32);
edittext.setEms(50);
return edittext;
}
private EditText createEditText()
{
final LayoutParams lparams = new LayoutParams(50,30); // Width , height
final EditText edittext = new EditText(this);
edittext.setLayoutParams(lparams);
return edittext;
}
Try this.
edittext.getLayoutParams().width=32;
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
final float height = metrics.heightPixels;
EditText edittext = new EditText(this);
edittext.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,(int) (height/2)));
RelativeLayout.LayoutParams.width = 32;
RelativeLayout.LayoutParams.height = 50;
works for me. for example
lparams.width = 32;
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) edittext.getLayoutParams();
params.width = mScreenWidth / 5;
params.height = mScreenWidth / 5;
edittext.setLayoutParams(params);
Try the following code:-
Display display = getWindowManager().getDefaultDisplay();
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
profile_pic.getLayoutParams().height=(screenHeight/6);
profile_pic.getLayoutParams().width=(screenHeight/6);