CQM
CQM

Reputation: 44268

android tablelayout trouble, adding views

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

Upvotes: 0

Views: 263

Answers (1)

MattDavis
MattDavis

Reputation: 5178

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

Upvotes: 1

Related Questions