Android编程权威指南 - 第7章 UI fragment与

2016-11-16  本文已影响70人  JMasche

引入fragment的原因

fragment的兼容性

最简单的fragment创建例子

例子说明

创建fragment的layout文件

此文件和之前Activity的没有区别,在一个LinearLayout中包含一个EidtText。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              
      android:layout_width="match_parent"              
      android:layout_height="match_parent"    
      android:orientation="horizontal" >    
      <EditText        
            android:id="@+id/crime_title"        
            android:layout_width="match_parent"        
            android:layout_height="match_parent"        
            android:hint="@string/crime_title_hint" />
</LinearLayout>

创建一个fragement类

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {    
      View v = inflater.inflate(R.layout.fragment_crime, parent, false);
      return v;
}

fragment中关联组件

mTrueButton = (Button)findViewById(R.id.true_button);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {    
      View v = inflater.inflate(R.layout.fragment_crime, parent, false);    
      mTitleField = (EditText)v.findViewById(R.id.crime_title);    
      mTitleField.addTextChangedListener(new TextWatcher() {        
            public void onTextChanged(CharSequence c, int start, int before, int count) {            
                  mCrime.setTitle(c.toString());        
            }        
            public void beforeTextChanged(CharSequence c, int start, int count, int after) {        
            }        
            public void afterTextChanged(Editable c) {       
             }    
      });    
      return v;
}

将UI fragment添加到Activity中

Activity托管UI fragment的两种方式

通过android.app.FragmentManager管理fragment

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"             
      android:id="@+id/fragmentContainer"             
      android:layout_width="match_parent"               
      android:layout_height="match_parent" />
FragmentManager fm = getFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
public class CrimeActivity extends Activity {    
      @Override    
      protected void onCreate(Bundle savedInstanceState) {        
            super.onCreate(savedInstanceState);        
            setContentView(R.layout.activity_crime);        
            FragmentManager fm = getFragmentManager();        
            Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);        
            if (fragment == null) {            
                  fragment = new CrimeFragment();            
                  fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();        
            }    
      }
}

FragmentManager与fragment的生命周期

各种场景下的调用说明

FragmentManager管理生命周期的特点

上一篇 下一篇

猜你喜欢

热点阅读