7

TextViewを含むLinearLayoutがあり、常にそうなります。また、TextViewの下には常に少なくとも1つのボタンがありますが、特定の状況では複数のボタンがある場合があります。

プログラムで必要な数のボタンを正常に作成して追加できます。また、これらのボタンに必要な外観関連のパラメーター/オプションをプログラムで正常に設定することもできます。

問題は、プログラムで作成されたボタンに、これらのパラメーターをプログラムで設定する代わりに、外観とレイアウトのパラメーターを含むXMLリソースファイルを使用するように指示する方法がわからないことです。

私は同じような名前の質問を見て、API自体をいじくり回して時間を費やしましたが、役に立ちませんでした。

編集:
これが私がやろうとしていることの概算であり、うまくいけば説明が少し明確になるでしょう:

private TextView textView;
private SomeObject someObject;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) {
    View scrollView = inflater.inflate(R.layout.fragment_play_game, container, false);
    textView = (TextView) scrollView.findViewById(R.id.game_data_text);
    textView.setText(someObject.getTextForTextView());

    LinearLayout layout = (LinearLayout) scrollView.findViewById(R.id.game_data_container);
    for (String optionText : someObject.getTextForButtons()) {
        layout.addView(createOptionButton(optionText, layout));
    }
    return scrollView;
}

private View createOptionButton(String optionText, LinearLayout layout) {
    Button optionButton = new Button(this.getActivity());
    // set button layout/options here, somehow??
    optionButton.setText(optionText);
    return optionButton;
}

フラグメントのXMLレイアウトファイルは次のようになります(ボタンを追加しようとしているのはこのLinearLayoutです)。

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/game_data_container"
        etc... >

        <TextView 
           android:id="@+id/game_data_text"
           etc... />

    </LinearLayout>

</ScrollView>

また、ボタンのXMLレイアウトファイル(custom_button.xmlと呼びます)を作成する場合、次のようになりますか?:

<?xml version="1.0" encoding="utf-8"?>
    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/play_game_option_button"
        etc... />

更新:
MrFox @が話していることを少し拡張するために、それを機能させるために私がしたことは、次の行を置き換えることでした。

Button optionButton = new Button(this.getActivity());

これで:

Button optionButton = (Button) inflater.inflate(R.layout.play_game_option_button, layout, false);

...これは、ボタンレイアウト(ボタンテンプレート)のみを含むxmlファイルを拡張します。この場合、ファイルのボタンの上に親がないため、そのファイルのルートビューが返されます。これはボタンだけです。

ただし、最後のブール値(attachToParent)をtrueに設定した場合、ボタンが含まれるルートコンテナー(呼び出しに渡された「layout」変数)が返されます。

これで、このテンプレートを使用して、必要な数のボタンを作成できます。

4

2 に答える 2

5

XMLスタイルが適用されたボタンだけのレイアウトを作成し、それを線形レイアウトに膨らませることを考えましたか?

何かのようなもの:

inflater.inflate(R.layout.StyledButton、MyLinearLayout、true);

于 2012-09-14T17:42:38.930 に答える
1

下のボタンのxml/res/layout/my_button_layout.xml

<Button xmlns:android="http://schemas.android.com/apk/res/android"
   ... />

あなたの活動のコード

myButton = (Button)inflate.inflate(R.layout.my_button_layout, null);
myView.addView(myButton);
于 2016-03-19T19:32:37.637 に答える