Android 基础

文章目录

          • 刷新媒体库
          • 修改状态栏颜色
            • 修改字体颜色
            • 显示隐藏状态栏
          • 布局边框 outlineProvider
          • FragmentPagerAdapter 加载
          • TextView 设置 Drawable
          • 拍照快门声
          • toJsonTree
          • 输出堆栈
          • LIstView
          • 验证并初始化GLS
          • List 嵌套
          • SpannerString
          • 防抖动

刷新媒体库

class MediaUtils {

    companion object {

        /**
         * 刷新media显示,使用MediaScannerConnection.scanFile会导致MediaScanner ServiceConnectionLeaked低概率错误,因此改用广播的方式
         * 2017.11.17改为scanFile,改成广播的方式会导致SD卡内容无法及时刷新
         *
         * @param ctx
         * @param filePath
         */
        fun noticeMediaScanner(ctx: Context, filePath: String?) {

            if (null == filePath) {
                return
            }

            MediaScannerConnection.scanFile(
                    ctx,
                    arrayOf(filePath), null
            ) { _, _ -> }
        }

    }

    init {
        throw AssertionError("cannot be instantiated")
    }

}
修改状态栏颜色
    fun initStatusBar() {
        var statusBarView: View? = null
        if (statusBarView == null) {
            //利用反射机制修改状态栏背景
            val identifier = resources.getIdentifier("statusBarBackground", "id", "android")
            statusBarView = window.findViewById<View>(identifier)
        }
        if (statusBarView != null) {
            statusBarView.setBackgroundResource(R.drawable.top_bar_background)
        }
    }
修改字体颜色
 /**
     * 界面设置状态栏字体颜色
     */
    fun changeStatusBarTextImgColor(isBlack: Boolean) {
        if (isBlack) {
            //设置状态栏黑色字体
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        } else {
            //恢复状态栏白色字体
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
        }
    }
显示隐藏状态栏
    fun hideStatusBar() {
        window.decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
//                or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE)

        if (Build.VERSION.SDK_INT < 30) {
            window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
            window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        } else {
            val v = window.decorView
            val uiOptions = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN)

            v.setSystemUiVisibility(uiOptions)
        }

    }

    fun showStatusBar() {
        window.decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
    }
布局边框 outlineProvider
 android:outlineProvider="bounds"
   ViewOutlineProvider viewOutlineProvider = new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
               outline.setOval(0,0,mImg.getWidth(), mImg.getHeight());
            }
        };
        mImg.setOutlineProvider(viewOutlineProvider);
        mImg.setClipToOutline(true);
FragmentPagerAdapter 加载

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import com.proginn.base.BaseFragment;

import java.util.List;

public class BaseFragmentAdapter extends FragmentPagerAdapter {
    private List<BaseFragment> fragments;
    private String[] titles;
    private FragmentManager fm;


    public BaseFragmentAdapter(FragmentManager fm, List<BaseFragment> fragments, String[] titles) {
        super(fm);
        this.fm = fm;
        this.titles = titles;
        this.fragments = fragments;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        FragmentTransaction ft = fm.beginTransaction();
        for (int i = 0; i < getCount(); i++) {//通过遍历清除所有缓存
            final long itemId = getItemId(i);
            //得到缓存fragment的名字
            String name = makeFragmentName(container.getId(), itemId);
            //通过fragment名字找到该对象
            BaseFragment fragment = (BaseFragment) fm.findFragmentByTag(name);
            if (fragment != null) {
                //移除之前的fragment
                ft.remove(fragment);
            }
        }
        //重新添加新的fragment:最后记得commit
        ft.add(container.getId(), getItem(position)).attach(getItem(position)).commit();
        return getItem(position);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    /**
     * 得到缓存fragment的名字
     *
     * @param viewId
     * @param id
     * @return
     */
    private String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }
}
TextView 设置 Drawable
mTvWorkWay.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_selectmore_active, 0);
拍照快门声
var audioManager: AudioManager = requireActivity().getSystemService(Context.AUDIO_SERVICE) as AudioManager
var ringerMode = audioManager.getRingerMode()

mMediaActionSound = MediaActionSound()
mMediaActionSound.load(MediaActionSound.SHUTTER_CLICK)

//铃音模式
if (ringerMode == AudioManager.RINGER_MODE_NORMAL) {
   mMediaActionSound.play(MediaActionSound.SHUTTER_CLICK)
}
toJsonTree

//避免泛型擦除

  /**
     * 用于保存集合
     *
     * @param key  key
     * @param list 集合数据
     * @return 保存结果
     */
public static <T> boolean putListData(SharedPreferences sp, String key, LinkedList<T> list) {
		boolean result;
		SharedPreferences.Editor editor = sp.edit();
		JsonArray array = new JsonArray();
		Gson gson = new Gson();
		for (int i = 0; i < list.size(); i++) {
			JsonElement obj = gson.toJsonTree(list.get(i));
			array.add(obj);
		}
}
/**
  * 获取保存的List
  *
  * @param key key
  * @return 对应的Lis集合
  */
 public static <T> LinkedList<T> getListData(SharedPreferences sp, String key, Class<T> cls) {
     LinkedList<T> list = new LinkedList<>();
     String json = sp.getString(key, "");
     if (!json.equals("") && json.length() > 0) {
         Gson gson = new Gson();
         JsonArray array = new JsonParser().parse(json).getAsJsonArray();
         for (JsonElement elem : array) {
             list.add(gson.fromJson(elem, cls));
         }
     }
     return list;
 }

输出堆栈
        Writer writer = new StringWriter();

        PrintWriter printWriter = new PrintWriter(writer);

        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();

        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }

        printWriter.close();

        String result = writer.toString();
LIstView
public View getView(int position, View convertView, ViewGroup parent) {
		Holder holder;
		if (convertView == null) {
			holder = new Holder();
···
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
}
static class Holder {
		
}
验证并初始化GLS
private GLFrameSurface mGLSurfaceView;
private GLFrameRenderer mRenderer;
private boolean supportsEs2;


public class GLFrameSurface extends GLSurfaceView {
	String TAG = "GLFrameSurface";

	public GLFrameSurface(Context context) {
		super(context);
	}

	public GLFrameSurface(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	@Override
	protected void onAttachedToWindow() {
		
		Log.v(TAG, "surface onAttachedToWindow()");
		
		super.onAttachedToWindow();
		// setRenderMode() only takes effectd after SurfaceView attached to window!
		// note that on this mode, surface will not render util GLSurfaceView.requestRender() is
		// called, it's good and efficient -v-
		setRenderMode(RENDERMODE_WHEN_DIRTY);
		Log.v(TAG, "surface setRenderMode RENDERMODE_WHEN_DIRTY");
		
	}
}
private void initFusionGlSurface() {

        mGLSurfaceView = new GLFrameSurface(this);
        mGLSurfaceView.setVisibility(View.INVISIBLE);

        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
        supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;

        if (supportsEs2) {
            // Request an OpenGL ES 2.0 compatible context.
            mGLSurfaceView.setEGLContextClientVersion(2);
            mRenderer = new GLFrameRenderer(this, mGLSurfaceView);
            mGLSurfaceView.setRenderer(mRenderer);
        }

        mAnalyserIfrCameraShow.addView(mGLSurfaceView);
        // 这句代码很重要,没有它会出现异常情况;
        mGLSurfaceView.setZOrderMediaOverlay(true);

    }

List 嵌套
public class ScrollListView extends ListView {
	
	public ScrollListView(Context context) {
		super(context);
	}

	public ScrollListView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ScrollListView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
				MeasureSpec.AT_MOST);

		super.onMeasure(widthMeasureSpec, expandSpec);
	}
	
}

SpannerString

可点击,可变色字符串

  @NonNull
    public static SpannableString createAgreementString(
            @NonNull final Activity activity, @NonNull String format) {
        String smrz = new String("实名个人信息");
        String zxkf = new String("在线客服");
        String agreementString = String.format(Locale.ENGLISH, format, "实名个人信息认证", "在线客服");

        SpannableString spannableString = new SpannableString(agreementString);

        int smrzSI = agreementString.indexOf(smrz);
        int zxkfSI = agreementString.indexOf(zxkf);

        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(activity.getResources().getColor(R.color.app_color));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {

            }
        }, smrzSI, smrzSI+smrz.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(activity.getResources().getColor(R.color.app_color));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                RouterHelper.startWebView(activity, activity.getString(R.string.service_url));
            }
        }, zxkfSI, zxkfSI+zxkf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        return spannableString;
    }

防抖动
import android.os.SystemClock;

public class FastClickInterceptor {

    private static final long MIN_INTERVAL = 1000;

    private long mLastClickTime;

    public boolean shouldIntercept() {
        if (SystemClock.elapsedRealtime() - mLastClickTime < MIN_INTERVAL) {
            return true;
        }
        mLastClickTime = SystemClock.elapsedRealtime();
        return false;
    }
}

你可能感兴趣的:(Android,android,常用自查表)