編輯:關於Android編程
因為這裡涉及到了下面RadioButton的點擊處理,關鍵的就是虛線框的東西
package xiaoxu.com.lifeservice.avtivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import java.util.ArrayList;
import java.util.Arrays;
import xiaoxu.com.lifeservice.R;
import xiaoxu.com.lifeservice.frag.FirstPageFrag;
import xiaoxu.com.lifeservice.frag.TextFrag;
public class MainActivity extends BaseActivity {
String[] fragStr = {"FirstPageFrag"};
RadioButton firstPageBtn;
ArrayList fragTag;
int mCurrIndex = 0;
FragmentManager fragManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragManager = getSupportFragmentManager();
if(savedInstanceState == null) {
initData();
initView();
} else {
}
}
private void initView() {
firstPageBtn = (RadioButton) findViewById(R.id.firstPageBtn);
firstPageBtn.setChecked(true);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_btn);
radioGroup.setOnCheckedChangeListener(radioListener);
showFragment();
}
//向容器中添加碎片,並顯示。
//------------------------------------------------
private void showFragment() {
if(mCurrIndex == 3 ) {
return;
}
android.support.v4.app.FragmentTransaction transaction = fragManager.beginTransaction();
Fragment frag = fragManager.findFragmentByTag(fragTag.get(mCurrIndex));
if (frag == null) {
frag = getInstance();
}
for (int i = 0; i < fragTag.size(); i++) {
Fragment f = fragManager.findFragmentByTag(fragTag.get(i));
if (f != null && f.isAdded()) {
transaction.hide(f);//隱藏當前的Fragment,僅僅是設為不可見,並不會銷毀
}
}
if (frag.isAdded()) {
transaction.show(frag);
} else {
transaction.add(R.id.content_Area, frag, fragTag.get(mCurrIndex));
}
transaction.commitAllowingStateLoss();
fragManager.executePendingTransactions();
}
//---------------------------------------------
private void initData() {
mCurrIndex = 0;
fragTag = new ArrayList<>(Arrays.asList(fragStr));
}
private RadioGroup.OnCheckedChangeListener radioListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.firstPageBtn:
mCurrIndex = 0;
break;
case R.id.listBtn:
mCurrIndex = 1;
break;
case R.id.dataBtn:
mCurrIndex = 2;
break;
case R.id.myBtn:
mCurrIndex = 3;
break;
}
}
};
public Fragment getInstance() {
//if(mCurrIndex == 0 ) {
return new FirstPageFrag();
// }
// return null;
}
}
附上activity中用到的xml文件。
<framelayout android:id="@+id/content_Area" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent">
</framelayout>
-接下來創建一個碎片,並從xml中獲取到ViewPager 和 創建自定義view的實例。
package xiaoxu.com.lifeservice.frag;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import xiaoxu.com.lifeservice.R;
import xiaoxu.com.lifeservice.ui.tabStrip.PagerSlidingTabStrip;
/**
* Created by Administrator on 2016/4/30.
*/
public class FirstPageFrag extends Fragment {
ViewPager pager;
PagerSlidingTabStrip tabStrip;
final String[] TITLE = {"首頁", "新聞", "小說", "更多"};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pager, null);
pager = (ViewPager) view.findViewById(R.id.pager);
tabStrip = (PagerSlidingTabStrip) view.findViewById(R.id.tab);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
pager.setAdapter(new NewsAdapter(getChildFragmentManager()));
int pagerMargin =
(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
pager.setPageMargin(pagerMargin);
tabStrip.setPager(pager);
}
class NewsAdapter extends FragmentPagerAdapter {
public NewsAdapter(FragmentManager fm) {
super(fm);
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return new TextFrag();//根據標簽的position返回指定的frag。
}
@Override
public int getCount() {
return TITLE.length;
}
@Override
public CharSequence getPageTitle(int position) {
return TITLE[position % TITLE.length];
}
}
}
這裡用到的xml文件如下:
package xiaoxu.com.lifeservice.ui.tabStrip;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.net.IDN;
import java.util.Locale;
import xiaoxu.com.lifeservice.R;
/**
* Created by Administrator on 2016/5/1.
* 指示標簽
*/
/**
* pstsIndicatorColor 指示器顏色
* pstsUnderlineColor 在視圖底部占位線的顏色
* pstsDividerColor 標簽之間分隔線的顏色
* pstsIndicatorHeight 指示器的高度
* pstsUnderlineHeight 在視圖的底部占位線的高度
* pstsDividerPadding Top and bottom padding of the dividers
* pstsTabPaddingLeftRight 左右標簽間距
* pstsScrollOffset · 指示器相對被選中的標簽的偏移
* pstsTabBackground 標簽的背景,應該是一個StateListDrawable
* pstsShouldExpand 如果設置為true,每個標簽都給予同樣的weight,默認為false
* pstsTextAllCaps 如果為真,所有選項卡標題都是大寫,默認為true
* tabTextSize 標簽的文字大小
* tabTextColor 標簽的文字顏色
* selectedTabTextColor 被選中標簽的文字顏色
*/
public class PagerSlidingTabStrip extends HorizontalScrollView {
private LinearLayout.LayoutParams defaultTabLayoutParams;
private LinearLayout.LayoutParams expandedTabLayoutParams;
public ViewPager.OnPageChangeListener delegatePageListener;
private LinearLayout tabsContainer;
private ViewPager pager;
private int tabCount;
private int currentPosition = 0;
private int selectedPosition = 0; //當前選中項
private float currentPositionOffset = 0f;
private Paint rectPaint;
private Paint dividerPaint;
private int indicatorColor = 0xFF666666;
private int underlineColor = 0x1A000000;
private int dividerColor = 0x1A000000;
private int indicatorHeight = 8;//指示器的高度
private boolean shouldExpand = false;
private boolean textAllCaps = true;
private int scrollOffset = 52;
private int underlineHeight = 2;
private int dividerPadding = 12;
private int tabPadding = 24;
private int dividerWidth = 1;
private int tabTextSize = 12;
private int tabTextColor = 0xFF666666;
private int selectedTabTextColor = 0xFF666666;
private Typeface tabTypeface = null;
private int tabTypefaceStyle = Typeface.NORMAL;
private int lastScrollX = 0;
private int tabBackgroundResId = R.drawable.tab_strip_background_tab;
private Locale locale;
public PagerSlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setFillViewport(true);
setWillNotDraw(false);
tabsContainer = new LinearLayout(context);
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(tabsContainer);
DisplayMetrics dm = getResources().getDisplayMetrics();
//int ---> dp
scrollOffset = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
indicatorHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
underlineHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
dividerPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
tabPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
dividerWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
tabTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.pagerSlidTabStrip);
//選擇標簽的顏色
indicatorColor = ta.getColor(R.styleable.pagerSlidTabStrip_pstsIndicatorColor, indicatorColor);
//占位線顏色
underlineColor = ta.getColor(R.styleable.pagerSlidTabStrip_pstsUnderlineColor, underlineColor);
//標簽之間的分隔線顏色
dividerColor = ta.getColor(R.styleable.pagerSlidTabStrip_pstsDividerColor, dividerColor);
//指示器的高度
indicatorHeight = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsIndicatorHeight, indicatorHeight);
//占位線的高度
underlineHeight = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsUnderlineHeight, underlineHeight);
//Top and bottom padding of the dividers
dividerPadding = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsDividerPadding, dividerPadding);
//左右標簽間距
tabPadding = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsTabPaddingLeftRight, tabPadding);
//標簽選中移動的值
scrollOffset = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_pstsScrollOffset, scrollOffset);
//標簽的背景
tabBackgroundResId = ta.getResourceId(R.styleable.pagerSlidTabStrip_pstsTabBackground, tabBackgroundResId);
//如果設置為true,每個標簽都給予同樣的weight,默認為false
shouldExpand = ta.getBoolean(R.styleable.pagerSlidTabStrip_pstsShouldExpand, shouldExpand);
//如果為真,所有選項卡標題都是大寫,默認為true
textAllCaps = ta.getBoolean(R.styleable.pagerSlidTabStrip_pstsTextAllCaps, textAllCaps);
//標簽字體大小
tabTextSize = ta.getDimensionPixelSize(R.styleable.pagerSlidTabStrip_tabTextSize, tabTextSize);
//標簽字體顏色
tabTextColor = ta.getColor(R.styleable.pagerSlidTabStrip_tabTextColor, tabTextColor);
//選中的字體顏色
selectedTabTextColor = ta.getColor(R.styleable.pagerSlidTabStrip_selectedTabTextColor, selectedTabTextColor);
rectPaint = new Paint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Paint.Style.FILL);
dividerPaint = new Paint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStyle(Paint.Style.FILL);
defaultTabLayoutParams =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
expandedTabLayoutParams =
new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f);
if (locale == null) {
locale = getResources().getConfiguration().locale;
}
}
public interface IconTabProvider {
int getPageIconResId(int position);
}
public void setPager(ViewPager pager) {
this.pager = pager;
if (pager.getAdapter() == null) {
throw new IllegalStateException("page does not have Adapter ");
}
pager.addOnPageChangeListener(pageListener);
notifyDataSetChange();
}
private void notifyDataSetChange() {
tabsContainer.removeAllViews();
tabCount = pager.getAdapter().getCount();
for (int i = 0; i < tabCount; i++) {
if (pager.getAdapter() instanceof IconTabProvider) {
addIconTab(i, ((IconTabProvider) pager.getAdapter()).getPageIconResId(i));
} else {
addTextTab(i, pager.getAdapter().getPageTitle(i));
}
}
updateTabStyles();
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
currentPosition = pager.getCurrentItem();
scroll2Child(currentPosition, 0);
}
});
}
private void addTextTab(int i, CharSequence pageTitle) {
TextView tv = new TextView(getContext());
tv.setSingleLine();
tv.setText(pageTitle);
tv.setTextSize(tabTextSize);
tv.setGravity(Gravity.CENTER);
addTab(tv, i);
}
private void addIconTab(int i, int pageIconResId) {
ImageButton imageBtn = new ImageButton(getContext());
imageBtn.setImageResource(pageIconResId);
addTab(imageBtn, i);
}
private void addTab(final View view, final int position) {
view.setFocusable(true);
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
pager.setCurrentItem(position);
}
});
tabsContainer.addView(view, shouldExpand ? defaultTabLayoutParams : expandedTabLayoutParams);
tabsContainer.setPadding(tabPadding, 0, tabPadding, 0);
}
private ViewPager.OnPageChangeListener pageListener = new ViewPager.OnPageChangeListener() {
/**
* 滾動完成後回調
* */
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
currentPositionOffset = positionOffset;
currentPosition = position;
scroll2Child(position, (int) positionOffset * tabsContainer.getChildAt(position).getWidth());
invalidate();
if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset, positionOffsetPixels);
}
}
@Override
public void onPageSelected(int position) {
selectedPosition = position;
updateTabStyles();
if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
scroll2Child(pager.getCurrentItem(), 0);
}
}
};
public ViewPager getPager() {
return pager;
}
public ViewPager.OnPageChangeListener getDelegatePageListener() {
return delegatePageListener;
}
public void setDelegatePageListener(ViewPager.OnPageChangeListener delegatePageListener) {
this.delegatePageListener = delegatePageListener;
updateTabStyles();
}
public int getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(int currentPosition) {
this.currentPosition = currentPosition;
updateTabStyles();
}
public int getSelectedPosition() {
return selectedPosition;
}
public void setSelectedPosition(int selectedPosition) {
this.selectedPosition = selectedPosition;
updateTabStyles();
}
public float getCurrentPositionOffset() {
return currentPositionOffset;
}
public void setCurrentPositionOffset(float currentPositionOffset) {
this.currentPositionOffset = currentPositionOffset;
updateTabStyles();
}
public int getIndicatorColor() {
return indicatorColor;
}
public void setIndicatorColor(int indicatorColor) {
this.indicatorColor = indicatorColor;
updateTabStyles();
}
public int getUnderlineColor() {
return underlineColor;
}
public void setUnderlineColor(int underlineColor) {
this.underlineColor = underlineColor;
updateTabStyles();
}
public int getDividerColor() {
return dividerColor;
}
public void setDividerColor(int dividerColor) {
this.dividerColor = dividerColor;
updateTabStyles();
}
public int getIndicatorHeight() {
return indicatorHeight;
}
public void setIndicatorHeight(int indicatorHeight) {
this.indicatorHeight = indicatorHeight;
updateTabStyles();
}
public boolean isShouldExpand() {
return shouldExpand;
}
public void setShouldExpand(boolean shouldExpand) {
this.shouldExpand = shouldExpand;
updateTabStyles();
}
public boolean isTextAllCaps() {
return textAllCaps;
}
public void setTextAllCaps(boolean textAllCaps) {
this.textAllCaps = textAllCaps;
updateTabStyles();
}
public int getScrollOffset() {
return scrollOffset;
}
public void setScrollOffset(int scrollOffset) {
this.scrollOffset = scrollOffset;
updateTabStyles();
}
public int getUnderlineHeight() {
return underlineHeight;
}
public void setUnderlineHeight(int underlineHeight) {
this.underlineHeight = underlineHeight;
updateTabStyles();
}
public int getDividerPadding() {
return dividerPadding;
}
public void setDividerPadding(int dividerPadding) {
this.dividerPadding = dividerPadding;
updateTabStyles();
}
public int getTabPadding() {
return tabPadding;
}
public void setTabPadding(int tabPadding) {
this.tabPadding = tabPadding;
updateTabStyles();
}
public int getDividerWidth() {
return dividerWidth;
}
public void setDividerWidth(int dividerWidth) {
this.dividerWidth = dividerWidth;
updateTabStyles();
}
public int getTabTextSize() {
return tabTextSize;
}
public void setTabTextSize(int tabTextSize) {
this.tabTextSize = tabTextSize;
updateTabStyles();
}
public int getTabTextColor() {
return tabTextColor;
}
public void setTabTextColor(int tabTextColor) {
this.tabTextColor = tabTextColor;
updateTabStyles();
}
public int getSelectedTabTextColor() {
return selectedTabTextColor;
}
public void setSelectedTabTextColor(int selectedTabTextColor) {
this.selectedTabTextColor = selectedTabTextColor;
updateTabStyles();
}
public Typeface getTabTypeface() {
return tabTypeface;
}
public void setTypeface(Typeface typeface, int style) {
this.tabTypeface = typeface;
this.tabTypefaceStyle = style;
updateTabStyles();
}
public int getTabTypefaceStyle() {
return tabTypefaceStyle;
}
public void setTabTypefaceStyle(int tabTypefaceStyle) {
this.tabTypefaceStyle = tabTypefaceStyle;
updateTabStyles();
}
/**
* 更新選中時標簽的狀態
*/
private void updateTabStyles() {
for (int i = 0; i < tabCount; i++) {
View v = tabsContainer.getChildAt(i);
v.setBackgroundResource(tabBackgroundResId);
if (v instanceof TextView) {
TextView textView = (TextView) v;
textView.setTextColor(tabTextColor);
textView.setTextSize(tabTextSize);
textView.setGravity(Gravity.CENTER);
textView.setTypeface(tabTypeface,tabTypefaceStyle);
if (textAllCaps) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
textView.setAllCaps(true);
} else {
textView.setText(textView.getText().toString().toUpperCase(locale));
}
}
if (i == selectedPosition)
textView.setTextColor(selectedTabTextColor);
}
}
}
/**
* @param position 當前的標題的position
* @param offset 滾動的偏移量
* */
private void scroll2Child(int position, int offset) {
if (tabCount == 0) {
return;
}
int newX = tabsContainer.getChildAt(position).getLeft() + offset;
if (offset > 0 || offset > 0) {
newX -= scrollOffset;
}
if (newX != lastScrollX) {
scrollTo(newX, 0);
lastScrollX = newX;
}
}
/**
* 繪制占位線 和 指示線
* */
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode() || tabCount == 0) {
return;
}
rectPaint.setColor(underlineColor);
int height = getHeight();
//畫底線
canvas.drawRect(0, height - underlineHeight, tabsContainer.getWidth(), height, rectPaint);
//選中標簽下的線
rectPaint.setColor(indicatorColor);
View currentTab = tabsContainer.getChildAt(currentPosition);
float lineLeft = currentTab.getLeft();
float lineRight = currentTab.getRight();
//在滿足偏移量大於0 ,且有下一個標簽的時候
if (currentPositionOffset > 0 && currentPosition < tabCount - 1) {
View nextTab = tabsContainer.getChildAt(currentPosition + 1);
int nextTabLeft = nextTab.getLeft();
int nextTabRight = nextTab.getRight();
lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset) * lineLeft);
lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset) * lineRight);
}
canvas.drawRect(lineLeft, height - indicatorHeight, lineRight, height, rectPaint);
// 分割線
dividerPaint.setColor(dividerColor);
for (int i = 0; i < tabCount - 1; i++) {
View tab = tabsContainer.getChildAt(i);
canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(), height - dividerPadding, dividerPaint);
}
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
SaveState saveState = (SaveState) state;
super.onRestoreInstanceState(saveState.getSuperState());
selectedPosition = saveState.currentPosition;
requestLayout();
}
/**
* 系統回收activity之前回調
* */
@Override
protected Parcelable onSaveInstanceState() {
Parcelable parcelable = super.onSaveInstanceState();
SaveState saveState = new SaveState(parcelable);
saveState.currentPosition = selectedPosition;
return saveState;
}
static class SaveState extends BaseSavedState {
int currentPosition;
public SaveState(Parcelable source) {
super(source);
}
private SaveState(Parcel in) {
super(in);
currentPosition = in.readInt();
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(flags);
}
public static final Creator CREATOR = new Creator() {
@Override
public SaveState createFromParcel(Parcel source) {
return new SaveState(source);
}
@Override
public SaveState[] newArray(int size) {
return new SaveState[size];
}
};
}
}
繼上一篇時間和日期設置的示例之後,今天來介紹Android的布局組件中有關於時間和日期的設置的組件,希望對大家有所幫助。具體如下:時間日期設置組件:TimePicker、
當應用安裝到Android後,系統會根據每個應用的包名創建一個/data/data/包名/的文件夾,訪問自己包名下的目錄是不需要權限的,並且Android已經提供了非常簡
Android 軟鍵盤自動彈出與關閉在我們寫修改信息或者搜索,修改密碼等界面的時候,用戶進入這個界面的主要目的就是輸入修改/查找 某些信息,為了用戶體驗應該自動彈出軟鍵盤
前言團隊協作中,盡量保證各自代碼自己維護。這樣既能保證代碼編寫者在邏輯上的一慣性,也能避免修改不熟悉的代碼而引起bug問題。但即使是這樣的規避,也依然無法避免程序員之間代