创建Switch并将其添加到Layout

时间:2016-08-30 13:22:39

标签: java android

我有一个片段

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="10dp"
        android:id="@+id/switchLayout">
    </LinearLayout>
</FrameLayout>

并希望在加载片段后立即将开关添加到LinearLayout

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootview = inflater.inflate(R.layout.fragment, container, false);
    LinearLayout switchLayout = (LinearLayout) rootview.findViewById(R.id.switchLayout);

    Switch new_switch = new Switch(getActivity());
    new_switch.setText("test");
    new_switch.setChecked(true);
    switchLayout.addView(new_switch);

    return rootview;
}

但是当片段加载没有任何反应时,会显示LinearLayout,但切换不会出现,我也不会收到任何错误消息。

我已经尝试添加

new_switch.setLayoutParams(new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT)
);

但没有区别

注意:这是我在这里的第一个问题,希望它不是太愚蠢^^

1 个答案:

答案 0 :(得分:0)

我已尝试执行与您正在执行的操作相同的操作。

主要活动布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <FrameLayout
        android:id="@+id/containerFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

然后在MainActivity.java中:

FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.containerFragment, 
                new MyFragment()).commit();

MyFragment和片段布局与您描述的相同。

结果:

enter image description here