android tablelayout trouble, adding views

孤人 提交于 2019-12-25 08:24:37

问题


I am having trouble with View leader , I'm not sure what the second parameter is supposed to be

        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);

The problem is that my TextView is null, despite being a subview of leader.

Pretty confused about this issue, and this is my XML

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

            </TableLayout>

do I need to do more with the XML? I don't have need to include the tablerows in it do I?

R.id.leaderLayout is its own xml file, a linearlayout with that id


回答1:


Here's the developer page for the View constructors:

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

The second and third parameters for a View are used if you want this view to have certain attributes or styles set upon the creation of that view.

It looks like you actually want your variable leader to be inflated. This will take a layout defined in xml and assign it to dynamically created view. You said that your leaderLayout is a LinearLayout, so it would look something like this.

//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); 

The first parameter for inflate is R.layout.nameOfYourXmlFile. The second is the ViewGroup that will be the parent of your inflated View. Once this is done, you can use findViewById on leader to get the child views in your Xml file, add more children dynamically, and add it as a child of your TableRow.

Here's the developer page for LayoutInflator, in case you're curious about other usages of the inflate method.

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



来源:https://stackoverflow.com/questions/10622880/android-tablelayout-trouble-adding-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!