使用XML布局作为模板以编程方式创建android按钮

Rob*_*Rob 7 android android-layout android-xml android-button

我有一个包含TextView的LinearLayout,并且总是会.TextView下面始终至少有一个按钮,但在某些情况下可能会有多个按钮.

我可以通过编程方式成功创建和添加任意数量的按钮.我还可以通过编程方式成功设置这些按钮所需的任何外观相关参数/选项.

问题是我不知道如何告诉以编程方式创建的按钮它应该使用包含外观和布局参数的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;
}
Run Code Online (Sandbox Code Playgroud)

片段的我的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>
Run Code Online (Sandbox Code Playgroud)

另外,如果我要为按钮创建一个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... />
Run Code Online (Sandbox Code Playgroud)

更新:
只是为了扩展一下MrFox @正在讨论的内容,我为使其工作所做的就是更换这一行:

Button optionButton = new Button(this.getActivity());
Run Code Online (Sandbox Code Playgroud)

这一个:

Button optionButton = (Button) inflater.inflate(R.layout.play_game_option_button, layout, false);
Run Code Online (Sandbox Code Playgroud)

...膨胀只包含Button布局(按钮模板)的xml文件.在这种情况下,它返回该文件的根视图,它只是按钮,因为文件中的按钮上方没有父文件.

但是,如果我已经将最后一个布尔值(attachToParent)设置为true,它将返回按钮所在的根容器(这只是传递给调用的'layout'变量).

我现在可以使用此模板生成任意数量的按钮.

chr*_*lip 5

您是否考虑过将布局作为应用XML样式的按钮,然后将其扩展为线性布局?

就像是:

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