【问题标题】:Add background image to individual fragments将背景图像添加到单个片段
【发布时间】:2013-07-12 22:50:20
【问题描述】:

我有一个包含多个fragments 的应用程序,我想知道如何为每个fragment 添加不同的背景。我正在使用的布局具有可滚动的选项卡,它们都使用相同的 xml 文件。我还有一个用于设置视图的MainActivity 和一个为每个fragment 设置的adapter。我知道您可以使用带有android:background 或类似内容的xml 文件添加背景,并将其设置为主要活动中的视图,但我不知道如何对每个选项卡执行此操作。感谢您的帮助!

【问题讨论】:

  • 当您创建这些选项卡片段时,通过 Bundle 传递给它们一个 int 值或其他指示目标背景的东西。然后,您可以在 onCreateView() 方法中使用 getArguments() 来查看传入的值并设置正确的背景。
  • 我不明白你的问题:你想改变 Fragment 或 Tab 的布局?也许发布您的布局(或图像)会更有帮助。
  • 我希望每个片段都有不同的背景,这样当您滑动或按下不同的选项卡时,整个页面的背景都会发生变化

标签: android tabs android-fragments android-arrayadapter


【解决方案1】:

要为片段添加背景,您必须将其包装在某个容器中

<LinearLayout
        android:id="@+id/linearlayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ccc"
        android:layout_weight="1"
        android:orientation="vertical">
    <fragment android:name="com.example.simplefragmentexample.LayOutOne"
            android:id="@+id/frag_1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </LinearLayout>

如果您希望使用相同的 xml 文件,您应该以编程方式设置图像 LinearLayout l = (LinearLayout) findViewById(R.id.linearlayout01); l.setBackground(Image);

或使用多个带有android:background 的xml。

【讨论】:

    【解决方案2】:

    您可以使用 Fragment getView() 方法获取片段的根视图。然后,您可以使用 View 的 setBackground() 方法之一设置 View 的背景。例如为每个片段设置随机背景颜色:

    for ( Fragment f : fragments ) {
        f.getView().setBackgroundColor ( (new Random()).nextInt() );
    }
    

    PS:我从未使用过片段,因此我的回答可能是错误的。

    【讨论】:

    • 嘿安德里亚,谢谢你的回答。你能看看我的问题stackoverflow.com/questions/21181193/…我在设置背景图像时遇到问题,当我做 f.getView().setBackgroundResource(R.drawable.image) 它不会改变,同样当我做 f .getView().getBackground() 它返回 null。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2012-04-09
    • 2011-06-01
    • 2017-01-14
    • 2013-12-16
    • 1970-01-01
    相关资源
    最近更新 更多