show code block

顯示具有 fragment 標籤的文章。 顯示所有文章
顯示具有 fragment 標籤的文章。 顯示所有文章

2017年3月9日 星期四

third-party元件 ─ 網路下載圖片比較和簡易使用Fresco、Picasso 、Glide、ImageLoader

前言:

這幾天遇到OOM問題。
情況大概就是RecyclerView裡面跑大量的ImageView,導致崩潰。
RecyclerView我是寫在Fragment上面的,一開始我以為是因為Fragment沒有做好回收導致重複創建。

後來找到的問題,原來是網路下載圖片(ImageLoader)的方式緩存沒有做到釋放。
我更換了一下我讀取網路上圖片的的第三方,使用了Picasso發現問題就迎刃而解了!!

問了一下大家才發現如果對處理執行緒(Thread)不熟的話,不太推使用ImageLoader,它有一堆Leak的問題。
迷之聲:TMD緩存方式寫得天花亂墜的還不是一堆Leak


Android是比較推薦使用Glide和Picasso。



Glide和Picasso
使用起來其實大同小異。
在這邊大致上介紹一下使用方式:


重點程式碼:
在build.gradle(Module:app)內

Picasso
免不了的import:
compile 'com.squareup.picasso:picasso:2.5.2'

使用方式:
Picasso.with(context)
.load("http://i.imgur.com/DvpvklR.png")
.into(imageView);


Glide
免不了的import:
compile 'com.github.bumptech.glide:glide:3.7.0'

使用方式:
Glide.with(context)
        .load(url)
        .into(imageView);


兩個第三方很像吧,是不是都簡單的不要不要的!


Fresco
而Fresco是facebook自己釋出的圖片下載第三方,你自己一定體驗過facebook它們寫的app雖然用到大量的圖片,但卻不會有卡頓、Crash掉的問題,你就知道Fresco有多麼的強大了!

推薦使用:
Glide > Picasso > Fresco > ImageLoader
當然這是比較主觀的推薦,也須依你當下的需求來使用。
如果圖片量不大,個人覺得Picasso是首選,因為他比較瘦。
當你的App內有大量的圖片需要處理,首選就會是Fresco


我擷取它人一段文章讓你參考:

Picasso所能實現的功能Glide都能做到,只是所需設置不同。兩者的區別是Picasso比Glide體積小很多且圖像質量比Glide高,但Glide的速度比Picasso更快,Glide的長處是處理大型的圖片流,如gif、video,如果要製作視頻類應用,Glide當為首選。
Fresco
可以說是綜合了之前圖片加載庫的優點,其在5.0以下的內存優化非常好,但它的不足是體積太大,按體積進行比較:Fresco>Glide>Picasso,所以Fresco在圖片較多的應用中更能凸顯其價值,如果應用沒有太多圖片需求,不推薦使用Fresco。


文獻:



2016年12月21日 星期三

Fragment當Activity使用,在Fragment上設置Button

前言:

許多人會覺得,奇怪我不是已經呼叫(findViewById)了嗎?怎麼我在fragment上的按鈕都完全無效?

其實都忽略了rootView這件事情。
對fragment來說必須有底部View,才有辦法呼叫元件做事!




實作:
一開始創建一個Fragment,這會是你Fragment的onCreateView。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_blank, container, false);
}
之後把return的View額外拉到全域變數來
private View view;
這View就會是你的rootView了,這時候在fragment上面設置元件才會有效果。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_blank, container, false);
    return view;
}

開始控制元件囉。
在平時的findViewById前面加上rootview
Button yourButton=(Button)rootview.findViewById(R.id.button_fragment);

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_blank, container, false);
    button = (Button) view.findViewById(R.id.button_fragment);
    imageView = (ImageView) view.findViewById(R.id.show);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            imageView.setImageResource(R.drawable.hello);
        }
    });
    return view;
}
以下是專案所有CODE範例

MainActivity.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/hello"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="hello"
        android:text="Call Fragment" />
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/hello" />
</RelativeLayout>
MainActivity.Java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void hello(View view) {
        //最簡易創建fragment的方式
        //不建議這樣做,因為初始化(init) fragment的方式被簡略(new BlankFragment())
        //會造成在控制fragment上的麻煩
        //創建方式詳情請見
        //http://nikeru8.blogspot.tw/2016/06/fragment-activity-fragment-activity.html
        getFragmentManager()
                .beginTransaction()
                .add(R.id.container, new BlankFragment())
                .commit();
    }
}
example_fragment.xml  創建的Fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    android:clickable="true"
    tools:context="com.example.a015865.simplefragment.simpleExample">
    //android:clickable="true"防止點擊穿透
    <Button
        android:id="@+id/button_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Call ImageView" />
    <ImageView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>
simpleExample.java

public class simpleExample extends android.app.Fragment {
    private View view;
    private ImageView imageView;
    private Button button;
    public simpleExample() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.example_fragment, container, false);
        button = (Button) view.findViewById(R.id.button_fragment);
        imageView = (ImageView) view.findViewById(R.id.show);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageResource(R.drawable.hello);
            }
        });
        return view;
    }
}

Demo打包:







可能會遇到的問題:

當你創建了Fragment,在Activity呼叫它的時候發現跑紅字了?!


此時要注意你創建的Fragment繼承問題。


必須繼承android.app.Fragment
當然你只要在import的地方使用import android.app.Fragment;
就可以直接extends Fragment

不用extends android.app.Fragment那麼醜!






Fragment全集

Fragment的使用(一) ─ 在activity內放置Fragment

Fragment的使用(二) ─ 在activity內切換Fragment

Fragment 返回上一頁 - OnBackPressed

Fragment點擊穿透

Fragment當Activity使用,在Fragment上設置Button - 此篇


Fragment點擊穿透問題

Fragment點擊穿透問題



前言:
一言蔽之,發現很多人都有這問題。
之前會穿透真的是bug,後來的版本fragment已經做出相對應的修正。









實作:
主要程式碼
android:clickable="true"



在每個fragment布局內,偷加上這行。
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context="com.stanley.a015865.image.AboutStanley"
   
android:clickable="true"
   
>










這篇就短短的,有問題留言囉!




Fragment全集

Fragment的使用(一) ─ 在activity內放置Fragment

Fragment的使用(二) ─ 在activity內切換Fragment

Fragment 返回上一頁 - OnBackPressed

Fragment
點擊穿透

2016年12月20日 星期二

Fragment 返回上一頁 - OnBackPressed

Fragment 返回上一頁 - OnBackPressed

前言:
Fragment由於不繼承Activity,他無法使用到OnBackPressed這個方法。



@Override
public void onBackPressed() {

}
P.S.  OnBackPressed就是手機上內建的上一頁按鈕。



這也是為什麼我個人非常不喜歡用Fragment的原因,新手也實在不推薦使用。以我來說唯一的使用時機大概是ViewPager 的分頁模式,單純拿來跑圖用的。最單純,最不會有問題。

ViewPager分頁

返回鈕有個最單純的方法在之前的網誌介紹過了,這邊就不贅述,但那方法只能「指定」你要回到哪一頁,並不能做到真正的返回上一頁的效果。








實作:
 @Override
public void onBackPressed() {

    int count = getFragmentManager().getBackStackEntryCount();

    if (count == 0) {
        super.onBackPressed();
        //additional code
    } else {
        getFragmentManager().popBackStack();
    }
}

/**
*count 就是你開Fragment的分頁數量
*/


Fragment一定是依附著Activity生存的,這個OnBackPressed請寫在Activity內。


END!






就不提供Demo了,有問題請留言。

Fragment全集

Fragment的使用(一) ─ 在activity內放置Fragment

Fragment的使用(二) ─ 在activity內切換Fragment

Fragment 返回上一頁 - OnBackPressed

Fragment
點擊穿透




2016年6月16日 星期四

Fragment的使用(二) ─ 在activity內切換Fragment


Fragment的使用(二)
─ 在activity內切換Fragment


前言:

(更新聲明2017/03/08)
做個小聲明:在這邊建議太過複雜的畫面不要使用Fragment。
這聲明是流著淚打出來的,Fragment是個超級大坑,以後妳絕對會遇到各式各樣不可預期的爛帳。我敢說Fragment的絕對是Android最爛的設計知之一。

1、如果你拿Fragment作為你的分頁使用,最常見的問題就是OOM,分頁之間的切換導致Fragment不斷疊加。
參照:http://stackoverflow.com/questions/28483600/android-fragments-on-backstack-taking-up-too-much-memory

2、再來就是複雜、難以控制的的生命週期
參照:https://asce1885.gitbooks.io/android-rd-senior-advanced/content/wo_wei_shi_yao_zhu_zhang_fan_dui_shi_yong_android_fragment.html

不是我在這黑Fragment,上面聯結有一小段說道:
When Fragments were introduced, they sounded like the best idea of all times. Being able to display more than one activity at the same time, kinda. That was the selling point.
當Fragment剛被發明,當你的App想要展示多個Activity時,Fragment被認為是最好的使用方式。
So the whole world slowly started using Fragments. It was the new kid on the block. Everybody was using Fragments. If you were not using Fragments, chances were that "you were doing it wrong".
Fragment當時是一個新的功能,全世界開始慢慢使用它的當下,你只要沒有使用Fragment,就會有人認為你的作法不夠潮。
A few years and apps later, the trend is (thankfully) reverting back to more activity, less fragment. This is enforced by the new APIs (The ability to transition between activities without the user really noticing, as seen in the Transition APIs and such).
幾年過後,因為API的改動,人們開始傾向於改回使用Activity多於Fragment。
So, in summary: I hate fragments. I believe it's one of the worst Android implementations of all time, that only gained popularity because of the lack of Transition Framework (as it exists today) between activities. The lifecycle of a Fragment is, if anything, a ball of random callbacks that are never guaranteed to be called when you expect them.

總結:Fragment是Android 有史以來最爛的成就,Fragment會變得如此火熱的原因是因為他在切換畫面時的流暢度是Activity無法比擬的。

所以我的結論是:
複雜的頁面不要使用Fragment
主要的用途在ViewPager之間的轉換就好了。






為什麼要在Activity加入Fragment呢?
為了要做到兩件事。
一、主要目的是要讓App得執行畫面,可以隨著裝置的螢幕大小自動調整。

二、可以在一個Activity內作內容的切換。(本日實作)




 今日要實作的影片實例: 在Activity加入Fragment的實作。


今日的重點程式碼:
//宣告
private FragmentManager manager;
private FragmentTransaction transaction;
//透過下方程式碼,取得Activity中執行的個體。
manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
//呼叫commit讓變更生效。
        transaction.commit();



STEP 1─創建兩個fragment。



















在創建的過程中,紅框處請勿勾選,用不到。
















STEP 2─ Layout的布局


MainActivity佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.nikeru8.a11245.MainActivity">
//切換第一個Fragment的按鈕
    <Button
        android:id="@+id/Button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Fragment1" />
//切換第二個Fragment的按鈕
    <Button
        android:id="@+id/Button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Fragment2" />
//準備顯示Fragment的Layout視窗
    <LinearLayout
        android:id="@+id/center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"></LinearLayout>
</LinearLayout>







fragment_fragment 1 佈局
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.nikeru8.a11245.Fragment1">
 
    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="FRAGMENT1"
        android:textSize="50dp"/>

</FrameLayout>













fragment_fragment2 佈局
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.nikeru8.a11245.Fragment2">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Fragment2"
        android:textSize="50dp"/>



</FrameLayout>








STEP 3─Java程式碼

MainActivity.java
package com.example.nikeru8.a11245;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity  {

    private FragmentManager manager;
    private FragmentTransaction transaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//透過下方程式碼,取得Activity中執行的個體。
        manager = getSupportFragmentManager();
       

    }
      //換頁的按鈕設定
    public void onClick(View view) {
//透過下方程式碼,取得Activity中執行的個體。
        transaction = manager.beginTransaction();
        switch (view.getId()) {
            case R.id.Button1:
                Fragment1 fragment1 = new Fragment1();
                transaction.replace(R.id.center, fragment1, "fragment1");

                break;
            case R.id.Button2:
                Fragment2 fragment2 = new Fragment2();
                transaction.replace(R.id.center, fragment2, "fragment2");
                break;

        }
//呼叫commit讓變更生效。
        transaction.commit();
    }
}


簡單三步驟!完成囉!








此時會發現一個問題,如果操作者按了返回建,會直接跳出app。






這時候我們要做的是希望按了返回,能返回上一個fragment。



transaction.addToBackStack("fragment2");
這就是我們的魔法。

……程式碼省略……….
//換頁的按鈕設定
public void onClick(View view) {
        transaction = manager.beginTransaction();
        switch (view.getId()) {
            case R.id.Button1:
                Fragment1 fragment1 = new Fragment1();
                transaction.replace(R.id.center, fragment1, "fragment1");
                transaction.addToBackStack("fragment1");

                break;
            case R.id.Button2:
                Fragment2 fragment2 = new Fragment2();
                transaction.replace(R.id.center, fragment2, "fragment2");
                transaction.addToBackStack("fragment2");
                break;

        }
        transaction.commit();

    }
……程式碼省略……….

此時就能用返回建切換上一個Fragment了!



後續維護:
這篇沒有提供github,照著上面的做法應該做得出來,如果有任何問題再聯絡我!





Fragment全集
 

協程(coroutine) - 協程為什麼要學它?

 Coroutine 協程 再強調一次 協程就是由kotlin官方所提供的線程api //Thread Thread { }.start() //Executor val execu...