Cote Mounyo
Cote Mounyo

Reputation: 13975

How to add inflated view into custom tableLayout

In the past, whenever I create a custom table layout, I create the children views in java and then add them to the table using tableRow.addView(childView). Presently, instead of creating all my children views by hand, I created them in xml and then inflate them into the tableRow.

So for example I do

RelativeLayout gameView = (RelativeLayout) mInflater.inflate(R.layout.my_game,
            new RelativeLayout(context));
…  //edits to gameView
gameView.requestLayout();
((ViewGroup) gameView.getParent()).removeAllViews();
tableRow.addView(gameView);
addView(tableRow);

My problem however is this: If I leave out the line ((ViewGroup) gameView.getParent()).removeAllViews() then I get an error that the view already has a parent and that I must first call revomeView on the child's parent. Not able to find any method called removeView, I use removeAllViews. But then when I do, I get a NullPointerException on the parent.

So the question: how do I inflate a view and then add it to a table layout?

Upvotes: 0

Views: 901

Answers (1)

codeMagic
codeMagic

Reputation: 44571

Try changing this line

RelativeLayout gameView = (RelativeLayout) mInflater.inflate(R.layout.my_game,
        new RelativeLayout(context));

to

RelativeLayout gameView = (RelativeLayout) mInflater.inflate(R.layout.my_game,
        null);

Upvotes: 1

Related Questions