0

我正在使用ViewPageIndicator,但在代码中使用 XML 布局时遇到问题。通常我使用setContentView(R.layout.activity_main). 当然,我可以在代码中创建布局,但我更喜欢使用 XML 文件。

public final class FragmentOne extends Fragment {
    private static final String KEY_CONTENT = "FragmentOne";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        TextView text = new TextView(getActivity());
        text.setGravity(Gravity.CENTER);
        text.setText("some text");
        text.setTextSize(20 * getResources().getDisplayMetrics().density);
        text.setPadding(20, 20, 20, 20);

        LinearLayout layout = new LinearLayout(getActivity());
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        layout.setGravity(Gravity.CENTER);
        layout.addView(text);

        return layout;
    }
}
4

1 回答 1

2

onCreateView()您可以使用LayoutInflater传入的第一个参数来膨胀布局。

您的代码将如下所示:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.my_fragment_layout, container, false);
}
于 2013-08-05T16:50:23.623 回答