我从网络服务获取电话公司列表,我必须将其设置为textview,但问题是我没有像上面的图像那样对齐。如何实现它。
答案 0 :(得分: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();
}
});
基本上,我让系统在第一轮绘图中为我做布局和测量。然后使用现在可用的每个文本视图的宽度,我根据包装逻辑重置布局参数并再次进行布局。
尝试使用不同大小的文字,它会自动调整。我会说这个解决方案非常hacky但它确实有效。如果您对此不满意take a look at this。
答案 1 :(得分:0)
使用
android:textAlignment="textStart"