最近在做一個仿電商的APP,由于前面使用了Fragment技術,現(xiàn)在想要在一個Fragment中做出TabHost的界面效果,經(jīng)過查找資料找到了解決辦法,特分享出來!(新人勿噴?。?/p>
創(chuàng)新互聯(lián)公司是專業(yè)的新市網(wǎng)站建設公司,新市接單;提供成都網(wǎng)站建設、網(wǎng)站設計,網(wǎng)頁設計,網(wǎng)站設計,建網(wǎng)站,PHP網(wǎng)站建設等專業(yè)做網(wǎng)站服務;采用PHP框架,可快速的進行新市網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
首先要使用的控件是Support V4里面的控件,XML如圖
這個XML是從Support V4中找的控件,多出來的是自定義的動態(tài)滾動條。
下面是具體的代碼實現(xiàn),如下
public class FUNFragment extends Fragment implements OnTabChangeListener { public FUNFragment() { // Required empty public constructor } private FragmentTabHost mTabHost_fun; private String[] fun_tabs = new String[] { "推薦", "標簽","關注"}; private ImageView mImgScrollbar_fun; private float lastoffset_fun; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_fun, container, false); mImgScrollbar_fun = (ImageView) layout.findViewById(R.id.img_scrollbar_fun); initActionBar(); // initTabFragment(); initTabHost(layout); return layout; } private void initActionBar() { FragmentManager fm = getChildFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ActionFragment actionFragment = new ActionFragment(); ft.add(R.id.action_fun, actionFragment); actionFragment.setActionName("FUN"); ft.commit(); } //初始化FragmentTabHost public void initTabHost(View layout) { mTabHost_fun = (FragmentTabHost)layout.findViewById(android.R.id.tabhost); mTabHost_fun.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent); mTabHost_fun.setOnTabChangedListener(this); for (int i = 0; i < fun_tabs.length; i++) { View view = getActivity().getLayoutInflater().inflate( R.layout.fun_tabhost_item, null); TextView mTextView = (TextView) view.findViewById(R.id.tv_fun_tab); mTextView.setText(fun_tabs[i]); mTabHost_fun.addTab(mTabHost_fun.newTabSpec("tag" + i).setIndicator(view), RecFragment.class, null); } } @Override public void onTabChanged(String tabId) { int position = mTabHost_fun.getCurrentTab(); //設置滾動動畫條 setScrollAnimation(position); } //設置 private void setScrollAnimation(int position) { //獲取屏幕的寬度 WindowManager mWindowManager = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE); Display display = mWindowManager.getDefaultDisplay(); @SuppressWarnings("deprecation") int width = display.getWidth(); //獲取滾動條的偏移量 int offset = width/fun_tabs.length; //使用開源項目nineold設置滾動動畫 ObjectAnimator ofFloat = ObjectAnimator.ofFloat(mImgScrollbar_fun, "translationX", lastoffset_fun, position*offset); ofFloat.setInterpolator(new DecelerateInterpolator()); ofFloat.setDuration(500).start(); //前一次偏移的位置 lastoffset_fun = position*offset; } }
將此記錄下來,也是為自己學習Android做個留念。希望對剛學習Android的朋友有點幫助。