示例代碼
public class MainForActivity extends FragmentActivity implements OnClickListener{
private Button mTabWeixin;
private contentFragment mWeixin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWeixin = new contentFragment();
setContentView(R.layout.activity_main_for);
mTabWeixin = (Button) findViewById(R.id.tab_bottom_weixin);
// 設置默認的Fragment
setDefaultFragment();
}
private void setDefaultFragment() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
mWeixin = new contentFragment();
transaction.replace(R.id.id_content, mWeixin);
transaction.commit();
}
public class contentFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.content_fragment, container, true);
}
}
運行后發生異常,這段代碼是從網上找的,抄下來的,為什么會錯。最后發現是在使用 inflater.inflate(R.layout.content_fragment, container, true); 函數發生錯誤。
第三個參數為true,就將這個container作為根對象返回,否則僅僅將這個root對象的LayoutParams屬性附加到resource對象的根布局對象上,也就是布局文件resource的最外層的View上
因為我的代碼里是要把content_fragment放主頁面activity_main_for上的,主頁面是跟布局對象,調用inflate是為了得到view對象,然后附加到根對象content_fragment的布局上的。所以第三個參數要改成false
另外介紹一下android LayoutInflater.inflate()的參數及其用法
LayoutInflater類的用法,以及inflate()方法參數的含義,解釋如下:
inflate()的作用就是將一個用xml定義的布局文件查找出來,注意與findViewById()的區別,inflate是加載一個布局文件,而findViewById則是從布局文件中查找一個控件。
1.獲取LayoutInflater對象有三種方法
LayoutInflater inflater=LayoutInflater.from(this);
LayoutInflater inflater=getLayoutInflater();
LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
2.關於LayoutInflater類inflate(int resource, ViewGroup root, boolean attachToRoot)方法三個參數的含義
resource:需要加載布局文件的id,意思是需要將這個布局文件中加載到Activity中來操作。
root:需要附加到resource資源文件的根控件,什么意思呢,就是inflate()會返回一個View對象,如果第三個參數attachToRoot為true,就將這個root作為根對象返回,否則僅僅將這個root對象的LayoutParams屬性附加到resource對象的根布局對象上,也就是布局文件resource的最外層的View上,比如是一個LinearLayout或者其它的Layout對象。
attachToRoot:是否將root附加到布局文件的根視圖上