Android:更改片段的背景色 [英] Android: Change Background Color of Fragment

查看:78
本文介绍了Android:更改片段的背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试更改片段的背景颜色,但是出现了一个小问题.

I tried changing the background color of a fragment, but a small problem occurred.

public class MainActivity extends FragmentActivity {

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

因此,上方所示是我为主类调用的XML文件片段的代码.

So, shown above is the code I had for my main class that calls the XML file for the fragment.

<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>

上方是主类(MainActivity)调用的main.xml布局.

Above is the main.xml layout that is called by the main class (MainActivity).

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

上方带有片段的XML文件称为此类.

Above the XML file with the fragment calls this class.

<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

This layout above is inflated by the class FirstFragment

那么,为什么这实际上不改变片段背景的颜色?

So, why doesn't this actually change the color of the background of my fragment?

推荐答案

片段不从View继承,因此没有设置的后台方法.

Fragments don't inherit from View and thus don't have a set background method.

任何简单的解决方法是仅获取根视图片段并设置背景

Any easy fix is to just grab the root view of fragment and set its background

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

这篇关于Android:更改片段的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆