的標準模式創建片段看起來是這樣的:
在你的片段類中(確保導入android.support.v4.app.Fragment):
public class MyFragment extends Fragment {
public static final String TAG = "MyFragment";
private int position;
// You can add other parameters here
public static MyFragment newInstance(int position) {
Bundle args = new Bundle();
// Pass all the parameters to your bundle
args.putInt("pos", position);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.position = getArguments().getInt("pos");
}
}
您的活動內幕:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Add your parameters
MyFragment fragment = MyFragment.newInstance(10);
// R.id.container - the id of a view that will hold your fragment; usually a FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.container, fragment, MyFragment.TAG)
.commit();
}
}
當你要訪問您的片段實例的公共方法,使用FragmentManager#findFragmentByTag(字符串標籤)找到你的片段的實例:
MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(MyFragment.TAG);
if(fragment != null){
// Do something with fragment
}
對於更詳細的解釋,我建議你閱讀關於碎片的官方文檔:https://developer.android.com/guide/components/fragments.html
你是什麼意思?你怎麼調用這個函數? – Piyush
@Puyish我編輯了這個問題 – Zidane