我有主要活动,我想在片段内调用方法,我使用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
}
}
最佳答案
您只需要从主活动内的片段中获取实例
MainFragment fragment=new MainFragment();