有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java textView将调整为tableLayout中最长的textView

当我向tableLayout中的一行添加文本视图时。。如果长度较长,它会调整之前所有的大小。我只想让每个文本视图都被包装成文本长度。。照片会更好地解释

        TableLayout ll = (TableLayout) findViewById(R.id.messhistory);
        TextView edit = new TextView(this);
        TableRow row = new TableRow(this);
        //edit.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        edit.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
        if(true)
        {
            ImageView iv= new ImageView(this);
            row.addView(iv);
            iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
        }
        row.addView(edit,new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
        ll.addView(row);

在添加更长的文本之前

enter image description here

添加长文本后

enter image description here


共 (2) 个答案

  1. # 1 楼答案

    你在任何地方都使用了相同的edit实例,所以下次当你的文本变大时,它会将较大的文本包装起来,因此它也会使(编辑)以前的实例变大。 一个可能的解决方案是每次添加文本时创建一个新的edit实例

  2. # 2 楼答案

    通过阅读有关TableLayout的文档,我得出以下结论:

    The width of a column is defined by the row with the widest cell in that column. However, a TableLayout can specify certain columns as shrinkable or stretchable by calling setColumnShrinkable() or setColumnStretchable(). If marked as shrinkable, the column width can be shrunk to fit the table into its parent object. If marked as stretchable, it can expand in width to fit any extra space.

    所以,你注意到的行为是故意的。但要获得类似的效果(没有固定的cloumn宽度),请尝试以下代码:

    // Define a Linearlayout instead of a TableLayout in your layout file
    // Set its width to match_parent
    // Set its orientation to "vertical"
    LinearLayout ll = (LinearLayout) findViewById(R.id.someLinearLayout);
    
    // This serves the same purpose as the TableRow
    LinearLayout llRow = new LinearLayout(this);
    
    TextView edit = new TextView(this);
    
    edit.setBackgroundDrawable(getResources().getDrawable(R.drawable.border));
    
    ImageView iv= new ImageView(this);
    
    llRow.addView(iv);
    
    iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
    
    LinearLayout.LayoutParams  llLeft = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
    
    LinearLayout.LayoutParams  llRight = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
    
    llLeft.gravity = Gravity.LEFT;
    
    llRight.gravity = Gravity.RIGHT;
    
    // You can set the LayoutParams llLeft(messages appear on left) or 
    // llRight(messages appear on right) Add "edit" first to make the imageview appear on right
    
    llRow.addView(edit, llLeft);
    
    ll.addView(llRow);