1

I'm trying to programmatically add TextViews to my layout. I want these TextViews to have a custom style, so I put this in res/layout/listitem_tpl.xml:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:textSize="25sp" >
</TextView>

Blindly following this answer with no real understanding of what I was doing, I put this in my onCreate:

LayoutInflater inflater = LayoutInflater.from(this);
TextView text = (TextView) inflater.inflate(R.layout.listitem_tpl, (ViewGroup) getWindow().getDecorView().getRootView());
text.setText("Hello, World!");

I wasn't sure what to put in for the second argument. I knew I needed the "parent view", which I assume is what I set with setContentView, but there's no getContentView so I cannibalized together that expression based on some information I found through googling. Is that line the problem?

In any case, the error I'm getting is:

12-24 11:52:12.370: E/AndroidRuntime(2677): Caused by: java.lang.ClassCastException: com.android.internal.policy.impl.PhoneWindow$DecorView cannot be cast to android.widget.Button

I looked up LayoutInflater.inflate and found that it should return a View. TextView is a subclass of View, so where's the problem?

Community
  • 1
  • 1
Jack M
  • 4,769
  • 6
  • 43
  • 67

2 Answers2

0

You have button in your xml

So type cast it in Button

LayoutInflater inflater = LayoutInflater.from(this);
Button text = (Button ) inflater.inflate(R.layout.listitem_tpl, (ViewGroup)getWindow().getDecorView().getRootView());
text.setText("Hello, World!");

EDIT

In 2nd argument of inflate function you are supposed to pass parent view for this view.

You can either pass null

TextView text = (TextView) inflater.inflate(R.layout.listitem_tpl, null);

and add it to the parent view

or pass the reference of the of the parent view there

vipul mittal
  • 17,343
  • 3
  • 41
  • 44
  • Typo. I was briefly testing with Buttons and forgot to change it back consistently for the question. Sorry. – Jack M Dec 24 '13 at 11:01
0

Just use this:

 LayoutInflater inflater = LayoutInflater.from(this);
 TextView text = (TextView) inflater.inflate(R.layout.listitem_tpl, null);
  text.setText("Hello, World!");

inflate method

parameter 1: resource ID for an XML layout resource to load (e.g., R.layout.main_page)
root Optional view to be the parent of the generated hierarchy.

Returns:
The root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.
Kailash Dabhi
  • 3,473
  • 1
  • 29
  • 47