我試圖弄清楚如何在viewpager中從imagebutton創建活動(有3個圖片按鈕)。我是一個初學者,並創建我的第一個應用程序。在Viewpager中創建活動 - Android Studio
這裏是我的main_java
private ViewPager mViewPager;
private DcDesignPageAdapter dcDesignPageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dc_design);
SectionsPagerAdapter(getSupportFragmentManager());
dcDesignPageAdapter = new DcDesignPageAdapter(getSupportFragmentManager(), getApplicationContext());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(dcDesignPageAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_dc_design, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
這裏是我的代碼片段
public class DcDesignFragment extends Fragment {
public static final String ImageButtonIDKey = "imagebuttonkey";
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(fragment_dcdesigns, container, false);
Bundle bundle = getArguments();
if(bundle != null) {
int imageButtonID = bundle.getInt(ImageButtonIDKey);
displayValues(view, imageButtonID);
}
return view;
}
private void displayValues(View view, int imageButtonID) {
ImageButton imageButton = (ImageButton) view.findViewById(R.id.imageButton);
imageButton.setImageResource(imageButtonID);
}
}
這裏是我的PageAdapter
String[] dcdesigns;
public DcDesignPageAdapter(FragmentManager fm, Context context) {
super(fm);
Resources resources = context.getResources();
dcdesigns = resources.getStringArray(R.array.dcdesigns);
}
@Override
public Fragment getItem(int position) {
Bundle bundle = new Bundle();
bundle.putInt(DcDesignFragment.ImageButtonIDKey,getDcdesignsImageButtonID(position));
DcDesignFragment dcDesignFragment = new DcDesignFragment();
dcDesignFragment.setArguments(bundle);
return dcDesignFragment;
}
private int getDcdesignsImageButtonID(int position) {
int id = 0;
switch (position) {
case 0:
id = R.drawable.1;
break;
case 1:
id = R.drawable.2;
break;
case 2:
id = R.drawable.3;
}
return id;
}
@Override
public CharSequence getPageTitle(int position) {
return dcdesigns[position];
}
@Override
public int getCount() {
return dcdesigns.length;
}
非常感謝你,任何幫助將不勝感激。
那麼,什麼是您所遇到的問題? – chRyNaN
我想在用戶點擊圖像按鈕時移動到另一個活動。 –
將onClickListener添加到ImageButton。調用getActivity()(從Fragment中)來獲取對Activity的引用,並使用傳入Intent的startActivity方法來啓動Activity。 – chRyNaN