我尝试更改 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/