I am creating buttons and adding them to a LinearLayout programmatically. However, I am struggling with changing the button sizes. In the code below, no matter what num I enter in deleteBtn.setWidth(num), and deleteBtn.setHeight(num), nothing changes.
private void populateHorizontalLayouts(CustomMessageEvent event) {
// Need to remove all views each time an user adds a number
// so that the same number is not rendered multiple times.
nameAndNumbersLayout.removeAllViews();
//displayedNamesAndNumbers.add(event.getCustomMessage());
for(int i =0; i < displayedNamesAndNumbers.size(); i++){
String displayedNumberAndName = displayedNamesAndNumbers.get(i);
LinearLayout horizontalLayout = new LinearLayout(view.getContext());
horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);
horizontalLayout.setId(i);
Button deleteBtn = new Button(view.getContext());
deleteBtn.setId(i);
deleteBtn.setText("Delete");
deleteBtn.setWidth(5);
deleteBtn.setHeight(5);
TextView nameAndNumView = new TextView(view.getContext());
nameAndNumView.setId(i);
nameAndNumView.setText(displayedNumberAndName);
horizontalLayout.addView(deleteBtn);
horizontalLayout.addView(nameAndNumView);
nameAndNumbersLayout.addView(horizontalLayout);
}
}
What should I write so that the button size changes?
You should apply LayoutParams of the LinearLayout which contains your Button.
deleteBtn.setLayoutParams(new LinearLayout.LayoutParams(5, 5));
Try this one
deleteBtn.setLayoutParams (new LayoutParams(LayoutParams.MATCH_PARENT, 15));
Try the following:
int pixels = Math.round(convertDpToPixel(50, getApplicationContext()));
deleteBtn.setLayoutParams(new LinearLayout.LayoutParams(pixels, pixels));
public static float convertDpToPixel(float dp, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return px;
}
You can set width and height using LayoutParams, generally when i manage with dimensions i use as reference screen's dimension.
Often i do something like this:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
float targetWidth = width / 3;
float targetHeight = targetWidth * 3;
deleteBtn.setLayoutParams(new LinearLayout.LayoutParams(targetWidth, targetHeight);
If you just want to change the height and keep the width as it is,
// This sets the height to 5 *pixels*, with keeping the width as it is.
deleteBtn.setLayoutParams (new LayoutParams(deleteBtn.getLayoutParams().getWidth(), 5));
and to change only width,
deleteBtn.setLayoutParams (new LayoutParams(5, deleteBtn.getLayoutParams().getHeight()));
Search for answer to a button [del] to be displayed in a Tablerow [tbrow], resulted only in setting the parameters for the Tablerow where the button appears.
del = new Button(getApplicationContext());
del.setText("DELETE");
del.setTextColor(Color.BLACK);
del.setGravity(Gravity.END);
del.setBackgroundColor(Color.parseColor("#FFFFC107"));
del.setLayoutParams (new TableRow.LayoutParams(80, 50));
tbrow.addView(del);
Related
I have a toggle button that changes it's size as following :
protected int[] calculateCardWidth(int[] rowsCols) {
//Getting the screen size.
Display display = this.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
//cardWidHigh 0->width , 1 ->height.
cardWidHigh[0] = (int) (width / (rowsCols[1] + .25));
cardWidHigh[1] = (int) (height / (rowsCols[0] + 2));
return cardWidHigh;
}
I want to be able to change the text size according to the change in button size (it's width and height )dynamically, what is the best approach inorder to achieve this ?
You change the values of its LayoutParams, the parent will use the new values to rerender the screen at new positions:
LayoutParams p = cardView.getLayoutParams();
p.width = cardWidth[0];
p.height = cardWidth[1];
cardView.setLayoutParams(p);
cardView.getViewParent().invalidate();
I want to set Max Height to Imageview that it can have when the image is loaded. Initial I've set android:height="wrap_content" in XML to make room for other views. But after the image is loaded sometimes it covers the whole screen of mobile and i can't see other views and i want to limit the height to some certain value. Please!! any help is appreciated.. cheers
A structure describing general information about a display, such as
its size, density, and font scaling.
DisplayMetrics metrics = getResources().getDisplayMetrics();
int DeviceTotalWidth = metrics.widthPixels;
int DeviceTotalHeight = metrics.heightPixels;
/*
*
* Adding Height Respect To Device
* */
ImageView ImageViewObj=(ImageView)findViewById(R.id.ImageViewId);
ImageViewObj.getLayoutParams().height= (int) (DeviceTotalHeight);
Get the screen height, and use it to set some ratio like Sunny said.
/* get the screen height in pixels */
public static int getScreenHeight(WindowManager windowManager) {
Display display = windowManager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
return point.y;
}
/* take an imageview, and set its height to desired float ratio */
public static void setImageHeight(Activity activity, ImageView imageView, float ratio) {
int h = getScreenHeight(activity.getWindowManager());
imageView.getLayoutParams().height = (int)(h*ratio);
}
Then in onCreate(....), try doing
ImageView imageView = (ImageView) findViewById(R.id.whatever);
setImageHeight(imageView, 0.4f); /* 40% */
I am trying to generate a button programatically in the center of the current view (which is the whole screen in this case). I get the screen height and width then find the center of the screen. Then I try to use the LayoutParams to set the top and left margins, taking into account the button size - but the result is not centered. What am I doing wrong?
public class StartActivity extends Activity {
private int cScreenWidth;
private int cScreenHeight;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
RelativeLayout ll = (RelativeLayout)findViewById(R.id.startLayout);
Display display = getWindowManager().getDefaultDisplay();
cScreenWidth = display.getWidth(); // deprecated but needed for API 10
cScreenHeight = display.getHeight(); // deprecated but needed for API 10
ImageButton myButton = new ImageButton(this);
myButton.setId(100);
myButton.setBackgroundResource(R.drawable.ic_launcher);
int size = Math.min(cScreenWidth / 3, cScreenHeight / 3);
LayoutParams lp = new LayoutParams( size, size );
lp.leftMargin = (cScreenWidth / 2) - (size / 2);
lp.topMargin = (cScreenHeight / 2) - (size / 2);
ll.addView(myButton, lp);
}
Try the following:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams)myButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
myButton.setLayoutParams(layoutParams);
This way you don't need to explicitly define the margins.
Alright I'm trying to build an activity that has a horizontal scrollview, that the user can swipe through, to view different "pages". My train of thought is these "pages" will be views. The following is a mockup of my idea (to mess around to see if it works)
I've experimented with this as follows:
My content view is set to the the scrollview. (unsure if this is an incorrect approach)
I create the scrollview, and place a view into it as follows:
private void setupScrollView()
{
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
int width = (int)MeasureUtils.convertDpToPixel(dpWidth, getApplicationContext());
int height = (int)MeasureUtils.convertDpToPixel(dpHeight, getApplicationContext());
_scrollView = new HorizontalScrollView(getApplicationContext());
_scrollView.setBackgroundColor(Color.CYAN);
_scrollView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Log.i("DEBUG", "Screen dp width = " + dpWidth + " screen dp height = " + dpHeight);
TextView view = new TextView(getApplicationContext());
view.setBackgroundColor(Color.RED);
view.setText("TEST");
view.setX(0); // Start at the left of the scrollview.
view.setWidth(width); // Size it so that it fills to the right of the scrollview.
TextView view2 = new TextView(getApplicationContext());
view2.setBackgroundColor(Color.GREEN);
view2.setText("TEST2");
view2.setX(width); // Start the second "page/view" offscreen to the right where i can scroll to it
view.setWidth(width); // Fill the screen width
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setBackgroundColor(Color.MAGENTA);
layout.addView(view);
layout.addView(view2);
_scrollView.addView(layout);
}
The idea above is that I will see a view, that takes up the screen, representing a page. This view should be "RED" in color. I can then scroll horizontally to the right and see the second view (view2) representing the next page. This view should be "GREEN" in color. This does not happen. I end up seeing what looks like 1/3rd or 1/2 of my screen being view1, the linearlayout taking up almost the whole screen (a bit of a gap to the right edge where the CYAN from the scrollview bleeds through).
Am I approaching this the wrong way, and/or is it possible to make this work the way I'm going at it?
You probably do not want to use a horizontalscroll view to create "pages".
Try looking at PageViewer
This automatically builds in all the sywpe and inflating logic for you.
Basically you will get a call to inflate a certain page. There you can then create your view (dynamically if you wish) and then just return the root to be rendered.
Alright I've figured out what I was doing wrong, and it turned out to be something very small...
The complete code is here:
private void setupScrollView()
{
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);
float density = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth = outMetrics.widthPixels / density;
int width = (int)MeasureUtils.convertDpToPixel(dpWidth, getApplicationContext());
int height = (int)MeasureUtils.convertDpToPixel(dpHeight, getApplicationContext());
_scrollView = new HorizontalScrollView(getApplicationContext());
_scrollView.setBackgroundColor(Color.CYAN);
_scrollView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Log.i("DEBUG", "Screen dp width = " + dpWidth + " screen dp height = " + dpHeight);
TextView view = new TextView(getApplicationContext());
view.setBackgroundColor(Color.RED);
view.setText("TEST");
view.setX(0);
view.setWidth(width);
view.setHeight(height - 50);
TextView view2 = new TextView(getApplicationContext());
view2.setBackgroundColor(Color.GREEN);
view2.setText("TEST2");
view2.setX(0);
view2.setWidth(width);
view2.setHeight(height - 50);
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setBackgroundColor(Color.MAGENTA);
layout.addView(view);
layout.addView(view2);
_scrollView.addView(layout);
}
This creates a horizontal scrollview programmatically, as I had, but the problem was that I was setting the second view to be "width" away, when it should be set to "0"as can be seen by:
view2.setX(0);
With that, I get 2 "views" that resemble pages in my scrollview that I can swipe through. Each taking up the whole page.
Hate having the code close and it being a simple fix that I missed :|
Hope this helps anyone else that tries to do it this way. I'm going to look into the PageViewer as Frank suggested.
My request is quite simple: I just want to display some text at a random place of the screen.
I was expecting, as I used:
int x = r.nextInt(width - layout.getWidth());
and
int y = r.nextInt(height - layout.getHeight());
that my layout would perfectly fit the screen.
Unfortunately, my text is sometimes at the right of the screen and appear in multiple lines!
Here is my code
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
layout.addView(clock);
layout.addView(txtView);
Random r = new Random();
int x = r.nextInt(width - layout.getWidth());
int y = r.nextInt(height - layout.getHeight());
layout.setPadding(x, y, 0, 0);
setContentView(layout);
Use RelativeLayout as your container instead of LinearLayout as this is what is is designed for.
The big problem I had was that
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
returns a value including the top statusBar (or notification, don't know how to call it) and the software buttons at the bottom.
The solution was to create a dummy layout in background and measure it.