【问题标题】:android layout - WRAP_CONTENT from right to left possible?android layout - WRAP_CONTENT 从右到左可能吗?
【发布时间】:2012-07-13 10:43:27
【问题描述】:

我在线性布局(水平)中有一个 TextView 和一个 ImageButton。我的总宽度是 300 像素。按钮图像为 50x50。我可以为文本使用的最大宽度是 250。如果文本宽度小于 250 像素(WRAP_CONTENT 很好用),下面的代码就可以完美运行。

    // 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);

文本占用超过 250 像素时会出现问题。按钮被推出并在 300 像素空间内变得不可见。

我想要的是:为图像分配 50 像素的宽度。 WRAP_CONTENT 在剩余的 250 个像素中。换句话说,不是从左边填写,而是从右边填写。在这种情况下使用重力是正确的吗?我应该在代码中如何以及在何处使用它?

或者还有其他更好的方法吗?

【问题讨论】:

  • 尝试文本视图的最大宽度属性
  • @zolio :除非必要并且您知道自己在做什么(换句话说,仅针对特定设备),否则切勿使用绝对像素。使用LinearLayoutslayout_weight 允许Android 分配屏幕的百分比。

标签: android layout


【解决方案1】:

使用相对布局而不是线性布局。设置每个View的LayoutParams如下:

// 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);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-08
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
相关资源
最近更新 更多