如果直接创建一个GridLayout,里面添加每一项,如果描述过长都导致显示不全,这个是系统的一个bug,计算的宽度有问题,因此需要对此方案进行更改。
更改方式为先计算左边占用的最大宽度,在添加右边的项时,设置布局参数控制最大的长度。
采用每一行一个布局,手动一行一行进行添加:
public class Typography5Activity extends BaseActivity { (Context context) { Intent intent = new Intent(); intent.setClass(context, Typography5Activity.class); context.startActivity(intent); } private LinearLayout root; private Paint leftPaint = new Paint(); private float textSize; private float maxLeftWidth; private int middlePadding = 0; @Override (Bundle savedInstanceState) { super.onCreate(savedInstanceState); root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.activity_typography5, null); setContentView(root); initPaint(); loadData(); } () { textSize = getResources().getDimensionPixelSize(R.dimen.text_size_13); leftPaint.setAntiAlias(true); leftPaint.setTextSize(textSize); leftPaint.setColor(getResources().getColor(R.color.color_black_999999)); middlePadding = getResources().getDimensionPixelSize(R.dimen.padding_value); } () { JSONArray array = DataSource.getArray(); calculateLeftMaxWidth(array); if (array != null) { try { int size = array.length(); for (int i = 0; i < size; ++i) { JSONArray o = (JSONArray) array.get(i); String key = o.getString(0); String value = o.getString(1); addItem(key, value); } } catch (Exception e) { } } } (JSONArray data) { try { int size = data.length(); for (int i = 0; i < size; ++i) { JSONArray o = (JSONArray) data.get(i); String key = o.getString(0); String value = o.getString(1); if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) { continue; } float curWidth = leftPaint.measureText(key); if (curWidth > maxLeftWidth) { maxLeftWidth = curWidth; } } maxLeftWidth = maxLeftWidth + middlePadding; } catch (Exception e) { } } (String key, String value) { LinearLayout layout = getItemLayout(); TextView left = (TextView) layout.findViewById(R.id.left); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.width = (int) maxLeftWidth; left.setLayoutParams(params); left.setText(key); TextView right = (TextView) layout.findViewById(R.id.right); right.setText(value); root.addView(layout); } private LinearLayout getItemLayout() { LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.compose_item_layout, null); return layout; } }