我需要一些帮助,使用当前片段的代码设置背景颜色。在选择特定选项卡时创建片段。
以下是我的主要活动代码
public class TabActionBarActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the text and background colour
setTheme(R.style.MyTheme);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
String label6 = getResources().getString(R.string.label6);
tab = actionBar.newTab();
tab.setText(label6);
TabListener<Tab6Fragment> tl6 = new TabListener<Tab6Fragment>(this,
label6, Tab6Fragment.class);
tab.setTabListener(tl6);
actionBar.addTab(tab);
String label7 = getResources().getString(R.string.label7);
tab = actionBar.newTab();
tab.setText(label7);
TabListener<Tab7Fragment> tl7 = new TabListener<Tab7Fragment>(this,
label7, Tab7Fragment.class);
tab.setTabListener(tl7);
actionBar.addTab(tab);
}
现在Tab7Fragment类的代码看起来像这样
public class Tab7Fragment extends Fragment {
TextView tv1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ScrollView sv = new ScrollView(this.getActivity());
LinearLayout ll = new LinearLayout(this.getActivity());
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
TextView tv = new TextView(this.getActivity());
tv.setText("Dynamic layouts ftw!");
ll.addView(tv);
EditText et = new EditText(this.getActivity());
et.setText("weeeeeeeeeee~!");
ll.addView(et);
Button b = new Button(this.getActivity());
b.setText("I don't do anything, but I was added dynamically. :)");
ll.addView(b);
for(int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(this.getActivity());
cb.setText("I'm dynamic!");
ll.addView(cb);
}
return this.getView();
}
}
现在我如何设置此片段的视图?
this.getActivity().setContentView(sv);
我知道上面的方法不正确。但我需要使用scrollview布局设置内容视图。另一个问题是如何为这个视图设置背景颜色?(使用setBackgroundColor()?
答案 0 :(得分:0)
在onCreateView()中尝试此代码:
View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
然后不要忘记返回刚刚膨胀到android运行时的视图。
删除return this.getView();
并添加return view;
答案 1 :(得分:0)
设置背景颜色:
sv.setBackgroundColor(getRessources().getColors(R.color.yourcolor));
要将布局扩展为片段,您需要从onCreateView返回一个View:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.your layout, container, false);
}