UI格局设计之加载xml

UI布局设计之加载xml

一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作,这需LayoutInflater动态加载
1. Activity中调用layout
1.setContentView(R.layout.main)
一旦调用, layout就会立刻显示UI
2.调用xml
mWidgetCanvas = (WidgetCellLayout) getFragmentManager().findFragmentById(
                R.id.canvas_content);
其中public final class WidgetCellLayout extends Fragment
Main.xml中定义
<fragment
        android:id="@+id/canvas_content"
        android:layout_width="@dimen/widget_canvas_width"
        android:layout_height="@dimen/widget_canvas_height"
        android:layout_alignParentTop="true"
        android:layout_gravity="center_horizontal"
        class="com.google.tv.launcher.ui.WidgetCellLayout" />
2. 非activity中操作layout
final  LayoutInflater inflater  =  LayoutInflater.from( mContext);
  LinearLayout layout  =  (LinearLayout) inflater.inflate(
                        R.layout.listview,  null ).findViewById(R.id.layout);
inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来
LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控件
 
                ListView lv = (ListView)layout.getChildAt( 0 );
或者
LayoutInflater mInflater = LayoutInflater.from(context);
View myView = mInflater.inflate(R.layout.customToast, null);
TextView sender = (TextView) myView.findViewById(R.id.sender);
TextView message = (TextView) myView.findViewById(R.id.message);