Android 常用方法摘記

調(diào)用系統(tǒng)方法,分享文本圖片等(2016-12-06 19:16:43)

/**
 * Created by _SOLID
 * Date:2016/4/22
 * Time:12:45
 * https://github.com/burgessjp/GanHuoIO/blob/master/app/src/main/java/ren/solid/ganhuoio/utils/ShakePictureUtils.java
 */
public class SystemShareUtils {

    public static void shareText(Context ctx, String text) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, text);
        sendIntent.setType("text/plain");
        ctx.startActivity(Intent.createChooser(sendIntent, "分享至"));
    }

    public static void shareImage(Context ctx, Uri uri) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
        sendIntent.setType("image/jpeg");
        ctx.startActivity(Intent.createChooser(sendIntent, "分享至"));
    }

    public static void shareImageList(Context ctx, ArrayList<Uri> uris) {
        Intent sendIntent = new Intent();
        sendIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
        sendIntent.putExtra(Intent.EXTRA_STREAM, uris);
        sendIntent.setType("image/*");
        ctx.startActivity(Intent.createChooser(sendIntent, "分享至"));
    }
}

Android調(diào)用微信掃一掃和支付寶掃一掃(2016-9-20 19:01:47)

摘自:習(xí)慣沉默的Blog

現(xiàn)在微信不能直接跳轉(zhuǎn)到微信掃一掃:詳見 Android調(diào)用微信掃一掃_(dá)CSDN

Gson構(gòu)造JsonArray(2016-8-23 16:11:25)

最近項(xiàng)目中請求參數(shù)傳參用到了 JsonArray對象
構(gòu)造方法如下:

    Object[] object = new Object[]{"111", "222", "24G"};
    JsonArray jsonArr = new JsonArray();
    for (Object anObject : object) {
        JsonObject jo = new JsonObject(); //構(gòu)造json
        jo.addProperty("offerCode", (String) anObject);
        jsonArr.add(jo);
    }
    Toast.makeText(this, "jsonArr:  " + jsonArr.toString(), Toast.LENGTH_SHORT).show();
    System.out.println("jsonArr:  " + jsonArr.toString());

訪問或者下載單個(gè)github文件(2016-9-20 18:43:37)

用途:可以用來存一些配置文件,圖片等.
url固定格式: https://raw.githubusercontent.com/username/repository/branch/filename
例如: https://raw.githubusercontent.com/yangxiaoge/MumuXi/master/README.md

參考stackoverflow:Download single files from GitHub

LICEcap錄制Gif工具(2016-8-2 18:57:50)

官網(wǎng)地址

錄制的gif圖

讀取Assets( 下面 cityId查詢天氣 中的是另一種讀取方法)目錄下文件(2016-06-12)

例如:

簡書:http://www.itdecent.cn/p/b87fee2f7a23

InputStreamReader isr = new InputStreamReader(this.getClass()
                    .getClassLoader()
                    .getResourceAsStream("assets/" + "student.json")
                    ,"utf-8"
                    );
//從assets獲取json文件
BufferedReader bfr = new BufferedReader(isr);

cityId查詢天氣(2016-6-20 19:00:35)

  1. citycode.txt是cityid文件(數(shù)據(jù) 101190101=南京 )
  2. 下面代碼是 逐行根據(jù)"="分隔符,讀寫城市id跟name,可以寫到文件中
    /**
     * 根據(jù)城市名找到對應(yīng)的id如果沒有則說明在中國氣象網(wǎng)不存在該城市
     *
     * @param cityname
     * @return
     */
    private String findId(String cityname) {
        if (null == cityname || "".equals(cityname))
            return null;
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open("citycode.txt"));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String[] str = new String[2];
            while ((line = bufReader.readLine()) != null) {
                str = line.split("=");
                if (str.length == 2 && null != str[1] && !"".equals(str[1]) && cityname.equals(str[1])) {
                    //返回對應(yīng)city編號(hào)
                    return str[0];
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

雙擊兩次返回鍵退出 (2秒內(nèi)退出)

private long exitTime = 0; // 返回鍵 退出時(shí)間
 /**
     *  返回鍵 (2秒內(nèi)退出)
     * @param keyCode 返回鍵code
     * @param event keyEvent
     * @return true
     */
 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            //兩秒之內(nèi)按返回鍵就會(huì)退出
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true; // 不要忘記 return true
        }

        return super.onKeyDown(keyCode, event);
}

下面是點(diǎn)擊返回鍵 關(guān)閉DrawerLayout等等

/**
     * 系統(tǒng)返回鍵監(jiān)聽,事件處理
     * @return
     */
    @Override
    public void onBackPressed() {
        HomeViewPagerFragment homeFragment = null;
        boolean isDrawerOpen = false;
        boolean isPopFragment = false;
        String currentTabTag = mTabHost.getCurrentTabTag();

        String homeName = getResources().getString(MainTab.HOME.getResName());

        String bundleName = getResources().getString(MainTab.BUNDLES.getResName());

        String billName = getResources().getString(MainTab.BILL.getResName());

        if (currentTabTag.equals(bundleName)) {
            isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(bundleName)).popFragment();
        } else if (currentTabTag.equals(billName)) {
            isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(billName)).popFragment();
        }

        if(currentTabTag.equals(homeName)){
            homeFragment= ((HomeViewPagerFragment)getSupportFragmentManager().findFragmentByTag(homeName));
            isDrawerOpen = homeFragment.isDrawerOpen();
        }

        if(isDrawerOpen){
            homeFragment.closeDrawer();
        }else if(!isPopFragment){
            finish();
        }
}

RadioButton 點(diǎn)擊事件 (2016-06-08)

借助ButterKnife快速實(shí)現(xiàn)

@OnCheckedChanged({R.id.searchRb1, R.id.searchRb2, R.id.searchRb3, R.id.searchRb4})
void onTagChecked(RadioButton searchRb, boolean checked) {
    if (checked) {
        //實(shí)現(xiàn)代碼...
    }
}

夜神 模擬器連接(2016-6-22 13:44:46)

流暢度杠桿的!

adb connect 127.0.0.1:62001

Fiddler抓包設(shè)置: 具體參考??trinea分享
1)

模擬器抓包配置

2)(實(shí)驗(yàn)證明已經(jīng)不需要這一步了,只要設(shè)置好代理服務(wù)器主機(jī)名就行了!! add 2016-8-16 16:09:01) 模擬器瀏覽器打開: http://10.45.16.34:8888/(10.45.16.34就是本機(jī)地址, 所有模擬器都是這么訪問)

海馬玩 模擬器連接(2016-06-14)

http://www.itdecent.cn/p/c2e6a4e7e9c4/comments/2742091#comment-2742091

adb connect 127.0.0.1:26944

抓包設(shè)置: 代理服務(wù)器主機(jī)名: 10.0.3.2 (genymotion也是這個(gè)), 夜神的是電腦ip

app啟動(dòng)頁面(AlphaAnimation漸變) (2016-06-14)

效果圖:

AlphaAnimation透明到不透明

完整代碼如下↓↓↓↓↓↓

public class StartActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final View view = View.inflate(this, R.layout.activity_start, null);
        setContentView(view);
        // 漸變展示啟動(dòng)屏 , 0.0-1.0 透明到不透明
        AlphaAnimation aa = new AlphaAnimation(0.1f, 1.0f);
        aa.setDuration(3000);
        view.startAnimation(aa);
        aa.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationEnd(Animation animation) {
                // 動(dòng)畫結(jié)束跳轉(zhuǎn)登陸界面
                redirectTo();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationStart(Animation animation) {
            }
        });
    }

    private void redirectTo() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
}

adapter中setTag()的使用

可以用來當(dāng)前方法中傳數(shù)據(jù)

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.temp, parent, false);
            holder.nameTv = (TextView) convertView.findViewById(R.id.name);
            holder.group = (RadioGroup) convertView.findViewById(R.id.group);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        HashMap<String, Object> map = getItem(position);
        map.put("position", position);
 --->   holder.group.setTag(map); // 通過group視圖設(shè)置setTag(map)
        ...
        ...
        ...
 --->   HashMap<String, Object> radioMap = (HashMap<String, Object>) group.getTag(); // getTag()

Gson把JsonArray的字符串轉(zhuǎn)成bean實(shí)體類

    String offerItemGroupStr;
    
    JsonArray array = (JsonArray) new JsonParser().parse(offerItemGroupStr);

    List<OfferItemGroup> offerDepGroupsList = new Gson().fromJson(array.toString(), new TypeToken<List<OfferItemGroup>>() {
        }.getType());

圓形進(jìn)度條(2016-7-1 13:20:24)

Float Button 圓形進(jìn)度條效果

week開源啦!! alibaba-week入口

保存圖片到本地文件(2016-7-11 12:35:51)

參考: Mumuxi代碼

/**
 * Created by allen on 2016/6/19.
 *
 *  Here reference is https://github.com/gaolonglong/GankGirl/blob/master/app/src/main/java/com/app/gaolonglong/gankgirl/util/ImageUtil.java
 */
public class ImgSaveUtil {

        public static Uri saveImage(Context context, String url, Bitmap bitmap, ImageView imageView, String tag){
            //妹紙保存路徑
            String imgDir = Environment.getExternalStorageDirectory().getPath() + "/GankGirl";
            //圖片名稱處理
            String[] fileNameArr = url.substring(url.lastIndexOf("/") + 1).split("\\.");
            String fileName = fileNameArr[0] + ".png";
            //創(chuàng)建文件路徑
            File fileDir = new File(imgDir);
            if (!fileDir.exists()){
                fileDir.mkdir();
            }
            //創(chuàng)建文件
            File imageFile = new File(fileDir,fileName);
            try {
                FileOutputStream fos = new FileOutputStream(imageFile);
                boolean compress = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                Snackbar.make(imageView,"妹紙已經(jīng)躺在你的圖庫里啦.. ( >ω<)", Snackbar.LENGTH_SHORT).show();

                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Uri uri = Uri.fromFile(imageFile);
            //發(fā)送廣播,通知圖庫更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));
            return uri;
        }
}

樣式統(tǒng)一設(shè)置 (2016-7-12 15:06:40)

例如:

 <!--全邊框 輸入框樣式-->
    <style name="edittext_style">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginLeft">@dimen/space_20</item>
        <item name="android:layout_marginRight">@dimen/space_20</item>
        <item name="android:layout_marginTop">@dimen/space_10</item>
        <item name="android:background">@drawable/input_bg</item>
        <item name="android:singleLine">true</item>
    </style>

    <!--只有底邊邊框 輸入框樣式-->
    <style name="edittext_style1" parent="edittext_style">
        <item name="android:background">?attr/editTextBackground</item>
    </style>

touch事件監(jiān)聽之tab頁再次點(diǎn)擊刷新數(shù)據(jù) (2016-7-15 14:23:06)

具體可以看 開源中國源碼: MainActivity

 @Override
    public boolean onTouch(View v, MotionEvent event) {
        super.onTouchEvent(event);
        boolean consumed = false;
        // use getTabHost().getCurrentTabView to decide if the current tab is
        // touched again
        if (event.getAction() == MotionEvent.ACTION_DOWN
                && v.equals(mTabHost.getCurrentTabView())) {
            // use getTabHost().getCurrentView() to get a handle to the view
            // which is displayed in the tab - and to get this views context
            Fragment currentFragment = getCurrentFragment();
            if (currentFragment != null
                    && currentFragment instanceof OnTabReselectListener) {
                OnTabReselectListener listener = (OnTabReselectListener) currentFragment;
                listener.onTabReselect();
                consumed = true;
            }
        }
        return consumed;
    }

ProgressDialog使用:例如登錄等待時(shí) (2016-7-15 14:55:24)

下面的代碼可以參考 Afrimax或者M(jìn)PT的[BaseActivity](https://coding.net/u/yangxiaoge/p/AfrimaxMI/git/blob/master/app/src/main/java/com/ztesoft/zsmart/datamall/app/base/BaseActivity.java)

// =======================DIALOG_CONTROL_INTERFACE START========================

    // dialog 是否處于可見狀態(tài)
    private boolean _isVisible;

    private ProgressDialog _waitDialog;

    @Override
    public void hideWaitDialog() {
        if (_isVisible && _waitDialog != null) {
            try {
                _waitDialog.dismiss();
                _waitDialog = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public ProgressDialog showWaitDialog() {
        return showWaitDialog(R.string.loading);
    }

    @Override
    public ProgressDialog showWaitDialog(int resid) {
        return showWaitDialog(getString(resid));
    }

    /**
     * 顯示耗時(shí)操作等待彈出框
     *
     * @param message 提示消息
     * @return ProgressDialog
     */
    @Override
    public ProgressDialog showWaitDialog(String message) {
        if (_isVisible) {
            if (_waitDialog == null) {
                _waitDialog = DialogHelp.getWaitDialog(this, message);
            } else if (_waitDialog != null) {
                _waitDialog.setMessage(message);
            }
            _waitDialog.show();
            return _waitDialog;
        }
        return null;
    }


    // =======================DIALOG_CONTROL_INTERFACE END==========================

遠(yuǎn)程調(diào)試App或者WiFi調(diào)試(2016-7-19 19:34:09)

http://www.itdecent.cn/p/e9c243b5060b

效果圖

ScrollView初始化數(shù)據(jù)時(shí)不置頂(2016-7-20 16:36:01)

ScrollView布局設(shè)置一個(gè)屬性即可!如果不設(shè)置,那么默認(rèn)顯示位置在ListView(等等..)底部
具體可以參考: ScrollView嵌套ListView不置頂顯示

mScrollView.smoothScrollTo(0, 0);

使用BroadCast發(fā)送廣播,通知home頁刷新數(shù)據(jù)(2016-7-29 13:05:32)

 //----------------發(fā)送廣播 , intent傳值--------------//
 private void sendRefreshAccountBroadcast() {
        Intent intent = new Intent(Constants.REFRESH_HOME_ACCOUNT_LIST);
        intent.putExtra(Constants.REFRESH_HOME_ACCOUNT_LIST, true);
        getBaseContext().sendBroadcast(intent);
    }
    
    

//----------------------接收廣播 start------------------//
 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getBooleanExtra(Constants.REFRESH_HOME_ACCOUNT_LIST, false)) {
                // 刷新數(shù)據(jù)
                initExpendListViewData();
            }
        }
    };

    
@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 注冊廣播監(jiān)聽
        IntentFilter filter = new IntentFilter(Constants.REFRESH_HOME_ACCOUNT_LIST);
        getActivity().registerReceiver(mReceiver, filter);
    }
//-------------------接收廣播 end------------------------//
    

EditText數(shù)據(jù)監(jiān)聽!登錄模塊,動(dòng)態(tài)搜索模塊等(2016-7-30 14:29:58)

    etUsertel.addTextChangedListener(new TextChange());
    etPassword.addTextChangedListener(new TextChange());

    // EditText監(jiān)聽器
    class TextChange implements TextWatcher {

        @Override
        public void afterTextChanged(Editable arg0) {

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                int count) {

            boolean Sign2 = et_usertel.getText().length() > 0;
            boolean Sign3 = et_password.getText().length() > 0;

            // 設(shè)置登錄按鈕的顏色,以及是否可點(diǎn)擊!
            if (Sign2 & Sign3) {
                btnLogin.setTextColor(0xFFFFFFFF);
                btnLogin.setEnabled(true);
            }
            // 在layout文件中,對Button的text屬性應(yīng)預(yù)先設(shè)置默認(rèn)值,否則剛打開程序的時(shí)候Button是無顯示的
            else {
                btnLogin.setTextColor(0xFFD0EFC6);
                btnLogin.setEnabled(false);
            }
        }

    }

AS快捷鍵(2016-8-2 18:58:02)

android_studio快捷鍵
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 曾經(jīng)有一份美好的愛情放在我的面前我沒有珍惜。等到失去后才后悔莫及。如果可以再對小李說。毛欣想說。這輩子無緣再牽手。...
    毛欣與小李閱讀 3,301評論 0 13
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,725評論 25 709
  • 國家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說閱讀 12,298評論 6 13
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,502評論 19 139
  • 又是超級幸福滿滿,感動(dòng)滿滿的一天。 來自一位關(guān)注我公眾號(hào)近一年的朋友。 那時(shí)候公眾號(hào)名還叫"娜樣安然",因?yàn)橐黄?..
    HR老白張小編閱讀 211評論 0 2

友情鏈接更多精彩內(nèi)容