私が見つけた解決策目標は、以前は別の場所でスタイル設定されていた要素をプログラムで作成することです。
まず、res/layoutフォルダーに新しい XML ファイルを作成しました。これにtemplate.xmlという名前を付け、次のコードを挿入しました。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
style="@style/rootElement"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/firstChildId"
style="@style/firstChild" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/secondChild" />
</LinearLayout>
そして、styles.xmlファイルで必要な方法でスタイルを設定しました
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="rootElement">
<!-- style -->
</style>
<style name="firstChild">
<!-- style -->
</style>
</resources>
さて、Activity クラスに以下を追加しました。
LinearLayout rootElement = (LinearLayout) getLayoutInflater().inflate(R.layout.template, null);
someOtherView.addView(rootElement);
インフレータは、res/layout/template.xml で作成したテンプレート (そのファイル内のすべての要素とその属性) を読み込み、それに割り当ててからrootElement
、私のコードで他の目的に使用します。例
TextView firstChild = (TextView) rootElement.getChildAt(0);
firstChild.setText("It is the firstChild element");
また
TextView firstChild = (TextView) rootElement.findViewById(R.id.firstChildId);
...
とても簡単ですね。それが役立つことを願っています