0
我很新的Android,學習了一下,我遇到了一個高於我的谷歌搜索技巧的問題。在片段中創建一個片段onClick
我有這樣的:用工具欄和viewPager
fragment_main與按鈕
主要活動
activity_main佈局這一點,主要是剝離的問題:
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private FragmentManager supportFragmentManager;
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//TextView textView = (TextView) rootView.findViewById(R.id.section_label);
//textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
Button newFragmentBtn = (Button) rootView.findViewById(R.id.cameraBtn);
newFragmentBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// create new fragment with same layout on right so I can swipe to it
}
});
return rootView;
}
public FragmentManager getSupportFragmentManager() {
return supportFragmentManager;
}
}
/**
* returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return 3;
}
}
}
所以我有現在3個片段(可能是任何數字),但我想這不是一個固定的數字,而是增加當我點擊按鈕時是在一個片段,所以,當我點擊newFragmentBtn,它創建4個片段之間滑動,再次點擊,5個片段等...
謝謝你的幫助。
[我如何將一個片段添加到ViewPager? addView崩潰我的應用程序](http://stackoverflow.com/questions/16232224/how-can-i-add-a-fragment-to-a-viewpager-addview-crashes-my-app) –
關鍵是' getCount'方法必須是動態的。讓'getItem'從列表中拉出來 –