我正在从网络服务获取电话公司列表,我必须将其设置为 textview,但问题是我没有像上图那样对齐。如何实现它。
问问题
698 次
2 回答
2
据我了解,您想在另一个旁边添加文本视图,但是当它们溢出(离开屏幕)时,下一个文本视图应该放在下一行。
这样做并非易事。实现这样的事情(最佳且正确)需要了解 android 如何绘制视图(onMeasure
和onLayout
)。但是,如果您不太关心效率(主要是因为您只为一小部分视图执行此操作),那么这是我的快速破解:
mContainer = (RelativeLayout) findViewById(R.id.container);
// first layout all the text views in a relative layout without any params set.
// this will let the system draw them independent of one another and calculate the
// width of each text view for us.
for (int i = 0; i < 10; i++) {
TextView tv = new TextView(getApplicationContext());
tv.setText("Text View " + i);
tv.setId(i+1);
tv.setPadding(10, 10, 20, 10);
mContainer.addView(tv);
}
// post a runnable on the layout which will do the layout again, but this time
// using the width of the individual text views, it will place them in correct position.
mContainer.post(new Runnable() {
@Override
public void run() {
int totalWidth = mContainer.getWidth();
// loop through each text view, and set its layout params
for (int i = 0; i < 10; i++) {
View child = mContainer.getChildAt(i);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// this text view can fit in the same row so lets place it relative to the previous one.
if(child.getWidth() < totalWidth) {
if(i > 0) { // i == 0 is in correct position
params.addRule(RelativeLayout.RIGHT_OF, mContainer.getChildAt(i-1).getId());
params.addRule(RelativeLayout.ALIGN_BOTTOM, mContainer.getChildAt(i-1).getId());
}
}
else {
// place it in the next row.
totalWidth = mContainer.getWidth();
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.BELOW, mContainer.getChildAt(i-1).getId());
}
child.setLayoutParams(params);
totalWidth = totalWidth - child.getWidth();
}
mContainer.requestLayout();
}
});
基本上,我让系统在第一轮绘图中为我完成布局和测量。然后使用现在可用的每个文本视图的宽度,我根据包装逻辑重置布局参数并再次进行布局。
尝试使用不同大小的文本,它会自动调整。我会说这个解决方案非常老套,但它确实有效。如果你不满意,看看这个。
于 2013-10-17T16:16:09.960 回答
0
利用
android:textAlignment="textStart"
于 2013-10-17T11:20:11.737 回答