【问题标题】:android tablelayout trouble, adding viewsandroid tablelayout麻烦,添加视图
【发布时间】:2012-05-17 01:22:37
【问题描述】:

我在使用 View leader 时遇到问题,我不确定第二个参数应该是什么

        TableLayout leaderTable = (TableLayout)findViewById(R.id.leaderTable);            

        TableRow tr = new TableRow(this);
        tr.setId(i);
        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

        View leader = new View(UserView.this, null, R.id.leaderLayout);

        TextView number = (TextView)leader.findViewById(R.id.numberView);
        number.setText(String.valueOf(i+1));

        tr.addView(leader);

        leaderTable.addView(tr);

问题是我的TextView 为空,尽管它是leader. 的子视图

对这个问题很困惑,这是我的 XML

<TableLayout 
                 android:id="@+id/leaderTable"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center">

            </TableLayout>

我需要对 XML 做更多的事情吗?我不需要在其中包含表格行吗?

R.id.leaderLayout 是它自己的 xml 文件,具有该 id 的线性布局

【问题讨论】:

    标签: android xml view android-linearlayout tablelayout


    【解决方案1】:

    这里是 View 构造函数的开发者页面:

    https://developer.android.com/reference/android/view/View.html#View%28android.content.Context%29

    如果您希望该视图在创建该视图时设置某些属性或样式,则使用视图的第二个和第三个参数。

    看起来您实际上希望您的变量 leader 被夸大。这将采用 xml 中定义的布局并将其分配给动态创建的视图。你说你的leaderLayout是一个LinearLayout,所以它看起来像这样。

    //Initialize the layout inflator, do this once and use it to inflate as many views as you want
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    
    //Assign your custom view to the variable leader
    LinearLayout leader = (LinearLayout) inflator.inflate(R.layout.leaderLayout, tr); 
    

    inflate 的第一个参数是 R.layout.nameOfYourXmlFile。第二个是将成为膨胀视图的父级的 ViewGroup。完成此操作后,您可以在 leader 上使用findViewById 来获取 Xml 文件中的子视图,动态添加更多子视图,并将其添加为 TableRow 的子视图。

    这是 LayoutInflator 的开发者页面,如果您对 inflate 方法的其他用法感到好奇。

    http://developer.android.com/reference/android/view/LayoutInflater.html

    【讨论】:

    • 我现在有一个新错误,这是我真正想做的codepad.org/3c4NNFlY,在forloop 的第二次通过时,addView 失败并显示05-16 13:34:05.143: E/AndroidRuntime(855): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 我想这永远不会成为问题,因为所有视图都是唯一的,并且在 for 循环的每次传递中创建
    • 方法inflate的第二个参数是膨胀视图的父级。因为一个视图不能是多个父视图的子视图,所以您会在addView 上收到错误,因为父视图已经设置。如果您将 tr 作为参数传递,它应该会自动添加,无需 addView。或者,您可以仅使用第一个参数(您的布局文件)调用 inflate,然后按原样调用 addView。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 2020-08-28
    • 2013-09-07
    相关资源
    最近更新 更多