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

7
我有一个LinearLayout,其中包含一个TextView,并且始终如此。 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;
}

我的 Fragment 的 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”变量)。现在,我可以使用此模板制作任意数量的按钮。
2个回答

5

你有没有考虑过创建一个仅包含已应用XML样式的按钮布局,然后将其填充到线性布局中?

类似于:

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


1
谢谢您的回复,我已经尝试了您建议的方法,但我不太明白如何实现您所建议的内容。我已经更新了我的原始问题并提供了更多信息。 - Rob
感谢@Rob对我的回答进行了补充! - chris-tulip
这非常完美,因为我需要设置一堆不同的属性,这些属性在 XML 文件中定义比在程序中编程更容易。 - Sepui

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接