小编Rob*_*Rob的帖子

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

我有一个包含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" …
Run Code Online (Sandbox Code Playgroud)

android android-layout android-xml android-button

7
推荐指数
1
解决办法
6988
查看次数