0

I have a TextView and an ImageButton in a linear layout (horizontal). Total width I have is 300 pixel. Button image is 50x50. Max width I can use for text is 250. The code below works perfect if the text width is less than 250 pixels (WRAP_CONTENT work nice).

    // create relative layout for the entire view
    LinearLayout layout = new LinearLayout(this);
    layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));
    layout.setOrientation(LinearLayout.HORIZONTAL);

    // create TextView for the title
    TextView titleView = new TextView(this);
    titleView.setText(title);
    layout.addView(titleView);

    // add the button onto the view
    bubbleBtn = new ImageButton(this);
    bubbleBtn.setLayoutParams(new LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
    layout.addView(bubbleBtn);

Problem comes when the text occupies more than 250 pixels. Button gets pushed out and becomes invisible within that 300 pixel space.

What I want is this: Allocate 50 pixels width for the image. WRAP_CONTENT in the remaining 250 pixels. In other words, instead of filling in from left, fill in from the right. Is Gravity the right thing to use in this context? How and where should I use it in the code?

Or any other better way of doing this?

zolio
  • 2,439
  • 4
  • 22
  • 34
  • try max width property of text view – Som Jul 13 '12 at 10:44
  • @zolio : Never use absolute pixels unless necessary and you know what you're doing (in other words only targetting one particular device). Use `LinearLayouts` and `layout_weight` to allow Android to allocate percentages of the screen. – Squonk Jul 13 '12 at 10:48

1 Answers1

1

Use a RelativeLayout instead of a LinearLayout. Set the LayoutParams of each View as follows:

// add the button onto the view
bubbleBtn = new ImageButton(this);
bubbleBtn.setId(1); // should set this using a ids.xml resource really.
RelativeLayout.LayoutParams bbLP = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
bbLP.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
bbLP.addRule(RelativeLayout.CENTER_VERTICAL);
layout.addView(bubbleBtn, bbLP);

// create TextView for the title
TextView titleView = new TextView(this);
titleView.setText(title);
titleView.setGravity(Gravity.RIGHT);
RelativeLayout.LayoutParams tvLP = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tvLP.addRule(RelativeLayout.LEFT_OF, 1);
tvLP.addRule(RelativeLayout.CENTER_VERTICAL);
layout.addView(titleView, tvLP);
nmw
  • 6,664
  • 3
  • 31
  • 32
  • See this post for how to best set ids programmatically: http://stackoverflow.com/questions/3216294/android-programatically-add-id-to-r-id – nmw Jul 14 '12 at 08:42