请注意:我正在以编程方式创建所有内容,因此我不会在任何地方与LayoutInflater服务或其技巧混合。因为在基础上,我不想创建我想要在这里实现的单个layout.xml。
假设我有一个RelativeLayout,我在这个布局上添加了TextView和ImageView。现在,我想知道哪个方法应该覆盖RelativeLayout已经完成开发其最终尺寸的位置,以及我可以用它来执行TextView和ImageView的布局修改。
我尝试了很多方法,比如重写onLayout,onMeasure,onAttachedToWindow等。 我还尝试在RelativeLayout的ViewTreeGroup上附加onGlobalLayoutListener,并尝试设置其子视图的layoutParams。但是,我只能使用这个观察者一次,然后我要删除它,否则它会每3秒调用2000次。
但似乎没有任何工作正常。
任何人都可以对实现这一目标有所了解吗?
注2:请不要评论为“你到目前为止尝试了什么?”。正如我之前所说的那样,我尝试了很多东西,而且我无法粘贴所有我尝试过的东西。但是我仍然会提供一些关于如何修改视图的layoutParams的重要信息,以便您可以获得一个想法。
RelativeLayout rl = //assumed generated programmatically.
TextView tv = //assumed generated programmatically.
rl.setPadding(0,0,0,0); //i remove all the padding
rl.addView(tv);
//now once added I modify its layoutParams
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams)tv.getLayoutParams();
rlp.leftMargin = rl.getWidth() - 100;
rlp.width = 100;
rlp.height = LayoutParams.MATCH_PARENT;
//thats and I do the above in an overridden method of RelativeLayout and expect the TextView to appear at the right-most end with width 100 and height equal to the container layout's height.
此外,覆盖RelativeLayout的onLayoutParams可以正常工作,但它对tableView单元格无法正常工作。这是一个例子
//Definition of custom RelativeLayout
public class MyRelativeLayout extends RelativeLayout
{
TextView tv;
public MyRelativeLayout(Context context)
{
super(context);
tv = new TextView(context);
this.addView(tv);
}
@Override
public void onLayout(boolean changed, int l, int t, int r, int b)
{
super.onLayout(changed,l,t,r,b);
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams)tv.getLayoutParams();
rlp.width = 100;
rlp.leftMargin = this.getWidth() - 100;
rlp.height = LayoutParams.MATCH_PARENT;
}
}
//implementation of MyRelativeLayout as a cell in listView
public View getView(int index, View view, ViewGroup viewGroup)
{
MyRelativeLayout rl = (MyRelativeLayout)view;
if(rl==null)
{
rl = new MyRelativeLayout(viewGroup.getContext());
rl.setPadding(0,0,0,0);
rl.setMinimumHeight(100); //this is another useless special
//method of android that I've to always write to set the height
//of cell. Adding of layoutParams to define the cell size just
//won't work.
//Even though all this is done, the new cells that are visible in the
//list view on scroll will have improper size of textView, either the
//height is totally zero, or sometimes half the height of its layout,
//sometimes left aligned, sometimes right aligned.
}
return rl;
}
答案 0 :(得分:1)
好的,现在我看到了你的错误。您不能在onLayout方法中更改布局参数。这将是recoursivly调用,并没有预期的效果。你必须在里面写这样的东西:
@Override
public void onLayout(boolean changed, int l, int t, int r, int b)
{
tv.layout(r - 100, t, r, b);
}
此代码将元素定位在相对布局中。此时你的孩子已经测量了宽度。当您的更改布局参数更新时,您必须再次调用测量,布局和测量后。 或者你可以在这里使用一些更复杂的逻辑来指定元素的位置。