今天换新版本的ADT之后默认建立工程引入Fragment,之前对Fragment没有做过了解。
想学习一下,在Activity的onCreate方法中无论怎么获取Fragment都是null,代码如下:
protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "" + "ActionBarActivity onCreate"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_jnitest); if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment(), "myfragment") .commit(); } Log.d(TAG, "Fragment:"+getSupportFragmentManager().findFragmentById(R.id.container));
log打印出来是null,看过Fragment生命周期,知道这个时候可能Fragment还没创建完成有可能获取不到,换个地方试试,在Activity的onResume中,这里肯定创建完成。
protected void onResume() { Log.d(TAG, "" + "ActionBarActivity onResume"); Log.d(TAG, "Fragment:"+getSupportFragmentManager().<span style="font-family: Arial, Helvetica, sans-serif;">findFragmentById(R.id.container));</span> // TODO Auto-generated method stub super.onResume(); }
结果打印出来依然是null,查看Google Developer明明说可以获取的
public abstract Fragment findFragmentById (int
id)
Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction.
This first searches through fragments that are currently added to the manager's activity; if no such fragment is found, then all fragments currently on the back stack associated with this ID are searched.
Returns
- The fragment if found or null otherwise.
我E文比较差,我的理解是说,只要通过transaction的时候,给定的容器ID就可以获取到啊,可是一直就是null。
google stackoverflow上也有人问类似的问题,但几乎所有人答复都是不能这么用,findFragmentById只能在XML标记的那个ID中可以使用。
也就是说只有通过类似如下代码可以通过R.id.list进行搜索:
<fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" />
也就是说目前剩下的只能通过findFragmentByTag来搜寻了,创建的时候加一个myfragment标签
if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .add(R.id.container, new PlaceholderFragment(), "myfragment") .commit(); }
找到时候通过如下代码
Log.d(TAG, "Fragment:"+getSupportFragmentManager().findFragmentByTag("myfragment"));
遇到第二个问题是,我当时用的不是getSupportFragmentManager而是用的getFragmentManager结果获取的还是空。
我就搞不懂,getSupportFragmentManager和getFragmentManager的区别在哪里。
接着google之后,其实两个方法的功能是一模一样的,区别只在于版本的区别,假如你在AndroidManifest中配置的minSdk是小于14的,那么就应该使用getSupportFragmentManager。
如果是高于14(包含)的,就应该使用getFragmentManager。
原因在于使用的jar包不一样,我使用的是android-support-v4.jar。