Bra*_*ing 27 layout android background fragment
我尝试更改片段的背景颜色,但发生了一个小问题.
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,上面显示的是我为主类调用片段的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>
Run Code Online (Sandbox Code Playgroud)
上面是主类(MainActivity)调用的main.xml布局.
public class FirstFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.main, parent, false);
}
}
Run Code Online (Sandbox Code Playgroud)
带有片段的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>
Run Code Online (Sandbox Code Playgroud)
上面的这个布局是由FirstFragment类夸大的
那么,为什么这实际上不会改变我的片段背景的颜色?
小智 39
片段不从View继承,因此没有set background方法.
fragment.getView().setBackgroundColor(Color.WHITE);
Run Code Online (Sandbox Code Playgroud)
之所以不起作用,是因为片段的处理方式类似于活动.它是一个容器,是主要活动的子容器,用于显示其他项目.
你需要把android:background ="#CBA"放在保存TextView的实际布局中,而不是片段本身.像这样:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CBA"
android:orientation="horizontal" >
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="BLAHHHH" />
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
59421 次 |
最近记录: |