2016-02-22 16 views
5

Qual è la vera differenza tra:Android: Qual è la differenza tra View.inflate e getLayoutInflater(). Gonfia?

return context.getLayoutInflater().inflate(R.layout.my_layout, null); 

gonfiare un nuova visione della gerarchia dalla risorsa XML specificato.

e

return View.inflate(context, R.layout.my_layout, null); 

Gonfiare una vista da una risorsa XML. Questo metodo pratico avvolge la classe LayoutInflater, che offre una gamma completa di opzioni per l'inflazione della vista.

risposta

6

Entrambi sono uguali. La seconda versione è solo un metodo pratico e breve per eseguire l'operazione. Se si vede il codice sorgente di View.inflate() metodo, si trovano:

/** 
    * Inflate a view from an XML resource. This convenience method wraps the {@link 
    * LayoutInflater} class, which provides a full range of options for view inflation. 
    * 
    * @param context The Context object for your activity or application. 
    * @param resource The resource ID to inflate 
    * @param root A view group that will be the parent. Used to properly inflate the 
    * layout_* parameters. 
    * @see LayoutInflater 
    */ 
    public static View inflate(Context context, int resource, ViewGroup root) { 
     LayoutInflater factory = LayoutInflater.from(context); 
     return factory.inflate(resource, root); 
    } 

che in realtà fa lo stesso lavoro nel backend, il primo metodo di lei ha citato lo fa.

1

Essi sono gli stessi e fare stessa cosa

In View.java classe

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) { 
     LayoutInflater factory = LayoutInflater.from(context); 
     return factory.inflate(resource, root); 
    } 

e LayoutInflater.from(context) restituire l'oggetto LayoutInflator. che è lo stesso del metodo getLayoutInflator().

public static LayoutInflater from(Context context) { 
     LayoutInflater LayoutInflater = 
       (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     if (LayoutInflater == null) { 
      throw new AssertionError("LayoutInflater not found."); 
     } 
     return LayoutInflater; 
    }