Android:更改 fragment 的背景颜色

标签 android layout background fragment

我尝试更改 fragment 的背景颜色,但出现了一个小问题。

public class MainActivity extends FragmentActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

所以,上面显示的是我的主类的代码,它为 fragment 调用 XML 文件。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.northreal.practice.FirstFragment"
        android:layout_width="0dip"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#CBA" />

</LinearLayout>

上面是main.xml布局,被主类(MainActivity)调用。

public class FirstFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent,
            Bundle savedInstanceState) {
        return inflater.inflate(R.layout.main, parent, false);
    }
}

上面带有 fragment 的 XML 文件调用这个类。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
     >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BLAHHHH"
        android:layout_gravity="center_vertical" />

</LinearLayout>

这个布局上面被FirstFragment类膨胀

那么,为什么这实际上并没有改变我的 fragment 背景的颜色呢?

最佳答案

Fragment 不继承自 View,因此没有设置背景方法。

任何简单的解决方法就是 grab the root view fragment 并设置其背景

fragment.getView().setBackgroundColor(Color.WHITE);

关于Android:更改 fragment 的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11692162/

相关文章:

java - 如何在 android 中通过缩略图使图像淋浴变大?

android - 截取布局屏幕截图,WebView 在其中不可见

java - Android ListView 滚动时丢失背景颜色

css - firebug 布局面板中的这条红线是什么?

layout - Node.js Express 库中的布局是什么?

ios - 即使应用程序被终止或从 ios 后台删除,我如何才能继续更新我的位置?

image - 在matlab中将图像添加到动画中

android - 当我键入 'ThankYou' 时,像自动完成结果这样的自定义 MultiAutoCompleteTextView 必须建议我 'TY'

android - 索引附近的 Unicode 属性不正确

jquery - 构建时间表屏幕/网格;最好的插件/工具是什么?