Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建开关并将其添加到布局中_Java_Android - Fatal编程技术网

Java 创建开关并将其添加到布局中

Java 创建开关并将其添加到布局中,java,android,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_paren

我有一块碎片

<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会显示,但是开关不会出现,我也不会收到任何错误消息

我已经试着添加了

new_switch.setLayoutParams(new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT,
    LinearLayout.LayoutParams.WRAP_CONTENT)
);
但这没什么区别


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

我已经尝试执行与您所做的相同的操作,并且效果良好

主要活动布局:

<?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>
MyFragment和fragment布局与您描述的相同

结果:


您的目标是什么?我不确定,但由于您是通过编程方式创建开关的,因此您可能应该使用drawable或类似的工具。也许在插入后,交换机就在您的布局中,它没有图标,所以您可以看到it@Opoo我想基于配置创建开关(配置决定开关的数量及其标签),您是如何在布局上放置片段的?你是在使用FragmentManager还是在你放置的活动布局中?@j2ko我在使用FragmentManagerKay,谢谢,我很笨。线性布局的方向必须垂直,而不是水平,否则只能看到一个开关。我接受你的答案,因为它帮助我找到了问题所在。
<?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>
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.containerFragment, 
                new MyFragment()).commit();