首頁  >  文章  >  Java  >  如何在 Android 中以程式設計方式正確地將 TextView 加入 LinearLayout?

如何在 Android 中以程式設計方式正確地將 TextView 加入 LinearLayout?

Patricia Arquette
Patricia Arquette原創
2024-10-26 05:53:03248瀏覽

How to Correctly Add a TextView to a LinearLayout Programmatically in Android?

在Android 中以程式設計方式將TextView 新增至LinearLayout

在Android 開發中,經常需要將視圖動態新增至定義的佈局中一個XML 檔。本文探討了在程式碼中將 TextView 加入到預先定義的 LinearLayout 的過程。

問題:

使用者嘗試將TextView 新增至定義的LinearLayout XML 使用下列程式碼:

<code class="xml">View linearLayout = findViewById(R.id.info);
TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setId(5);
valueTV.setLayoutParams(new LayoutParams(
        LayoutParams.FILL_PARENT,
        LayoutParams.WRAP_CONTENT));

((LinearLayout) linearLayout).addView(valueTV);</code>

但是,此程式碼導致ClassCastException ClassCastException :

java.lang.ClassCastException: android.widget.TextView

解:

錯誤由於LinearLayout 變數的轉換不正確而發生。要存取 LinearLayout,應將其明確轉換為 LinearLayout:

<code class="xml">LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info);
...
linearLayout.addView(valueTV);</code>

此外,應使用 LinearLayout.LayoutParams 而不是 LayoutParams 建立 LayoutParams 實例。

修正的程式碼:

<code class="xml">LinearLayout linearLayout = (LinearLayout)findViewById(R.id.info);

TextView valueTV = new TextView(this);
valueTV.setText("hallo hallo");
valueTV.setId(5);
valueTV.setLayoutParams(new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.FILL_PARENT,
        LinearLayout.LayoutParams.WRAP_CONTENT));

linearLayout.addView(valueTV);</code>

透過進行這些更改,TextView 將成功新增至 LinearLayout。

以上是如何在 Android 中以程式設計方式正確地將 TextView 加入 LinearLayout?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn