LayoutInflater的inflate函數用法詳解

fmms 12年前發布 | 314K 次閱讀 Android Android開發 移動開發

LayoutInflater作用是將layoutxml布局文件實例化為View類對象。</p>

獲取LayoutInflater的方法有如下三種:

  • LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View layout = inflater.inflate(R.layout.main, null);

     

    LayoutInflater inflater = LayoutInflater.from(context); (該方法實質就是第一種方法,可參考源代碼)

    View layout = inflater.inflate(R.layout.main, null);

     

    LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,實際上是View子類下window的一個函數)

    View layout = inflater.inflate(R.layout.main, null);
    </div> </td> </tr> </tbody> </table> </div> </div> </div>

    一直有點糾結setContentViewinflate的區別找了一些資料。寫了個小程序看了下:

    public class MyInflate extends Activity{

        private TextView tv;

        public void OnCreate(Bundle savedInstanceState){

            super.onCreate(savedInstanceState);

            //setContentView(R.layout.main);

            //tv = (TextView) findViewById(R.id.tv);

     

            LayoutInflater inflate = LayoutInflater.from(this);

            View view = inflate.inflate(R.layout.main,null);

            setContentView(view);

        }

    }
    </div> </td> </tr> </tbody> </table> </div> </div> </div>

    上述注釋掉的代碼和沒有注釋掉的代碼兩種情況是相同的。

    區別:
    setContentView()
    一旦調用, layout就會立刻顯示UI;而inflate只會把Layout形成一個以view類實現成的對象,有需要時再用setContentView(view)顯示出來。一般在activity中通過setContentView()將界面顯示出來,但是如果在非activity中如何對控件布局設置操作了,這就需要LayoutInflater動態加載。

    public View inflate(int Resourece,ViewGroup root)
    作用:填充一個新的視圖層次結構從指定的
    XML資源文件中
    reSource
    ViewlayoutID
    root
     生成的層次結構的根視圖
    return 
    填充的層次結構的根視圖。如果參數root提供了,那么root就是根視圖;否則填充的XML文件的根就是根視圖。

    其余幾個重載的inflate函數類似。

    </span>

     本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
     轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
     本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!
  • sesese色