【发布时间】:2015-08-23 22:56:08
【问题描述】:
我有主要活动,我想在片段中调用方法我使用 getSupportFragmentManager 获取片段但总是返回 null 给我,你能帮我吗
主活动:
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity implements OnItemPressListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void A()
{
FragmentManager fragManager = this.getSupportFragmentManager();
MainFragment fragment= (MainFragment)fragManager.findFragmentById(R.id.mainfragment);///always Null
fragment.B();
}.
}
main_fragment:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mainfragment"
tools:context=".mainFragment">
<GridView
android:id="@+id/gridview_movie"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></GridView>
</FrameLayout>
MainFragmet:
import android.support.v4.app.Fragment;;
public class MainFragment extends Fragment {
public void B() {
///do some thing
}
}
【问题讨论】:
-
片段是否实际加载到
R.id.mainfragment中?您的MainActivity中没有任何代码建议您这样做。