Home >Java >javaTutorial >**How to Add a TextView to a LinearLayout in Android?**
Question:
In an XML-defined layout, a LinearLayout is declared to dynamically add TextViews. However, an attempt to do so results in a ClassCastException: android.widget.TextView error.
Answer:
To rectify the error, the following steps should be taken:
Cast the LinearLayout to the correct type:
<code class="java">LinearLayout linearLayout = (LinearLayout) findViewById(R.id.info);</code>
Ensure that the LayoutParams used for the TextView are LinearLayout.LayoutParams:
<code class="java">valueTV.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));</code>
Add the TextView to the LinearLayout:
<code class="java">linearLayout.addView(valueTV);</code>
The above is the detailed content of **How to Add a TextView to a LinearLayout in Android?**. For more information, please follow other related articles on the PHP Chinese website!