1
如何通過按鈕點擊事件上的標籤滑動?如何滑過按鈕上的標籤點擊
即即使按下了一個計算按鈕,用戶也會被移動到選項卡式活動中的另一個頁面上,從而爲他們提供結果。
public class MainActivity extends ActionBarActivity implements
android.support.v7.app.ActionBar.TabListener {
private ViewPager mViewPager;
//TODO: Find alternatives to deprecated methods
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
public void onClick(View view){
EditText weight_entry = (EditText) findViewById(R.id.weight_entry);
EditText height_entry = (EditText) findViewById(R.id.height_entry);
String weight = weight_entry.getText().toString();
String height = height_entry.getText().toString();
TextView calc_label = (TextView) findViewById(R.id.calc_label);
if (weight.matches("")|| height.matches("")){
return;
} else {
float t;
float w = Float.parseFloat(weight);
float h = Float.parseFloat(height);
//TODO: check this
t = (float)((double)Math.round(10D * (double)(w/(h * h)))/10D);
calc_label.setText("Your BMI is: " + Float.toString(t));
}
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(weight_entry.getWindowToken(), 0);
imm.hideSoftInputFromWindow(height_entry.getWindowToken(), 0);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new InputFragment();
case 1:
return new ResultFragment();
case 2:
return new HistoryFragment();
}
return null;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
這沒有奏效。我已經添加了上面的代碼。 – zacdevil10
好吧,顯然你有ViewPager,而不是一個標籤;) 試試這個 'mViewPager.setCurrentItem(IDX);' IDX去過,你要顯示的頁面的索引。我想你的情況會是'1' 在你的onClick上。 – Olaia
工作感謝 – zacdevil10