简体   繁体   中英

How to add an onTabListener for a tab in Android

I have an issue in my application. The issue is that I cannot switch between activities from one tab to another. Here is my code:

     public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
            String n = tab.getText().toString();
            Toast.makeText(getApplicationContext(), "You have selected: " + n, Toast.LENGTH_LONG).show();
            if (n =="Converter") {
                startActivity(new Intent ("com.example.currencyconverter.MainActivity"));
                }
            if (n =="Currencies") {
                startActivity(new Intent ("com.example.currencyconverter.FirstActivity"));  
            if (n=="News") {
                startActivity(new Intent ("com.example.currencyconverter.FirstActivity"));  
                  }
                }

        }

My app is crashing. What is the issue? Any help would be greatly appreciated.

Java does not compare string like C#

In Java it is

if(n.equals("Converter"))
{   /// do something }

Change your String comparisons to use equals and your

startActivity(new Intent ("com.example.currencyconverter.MainActivity"));

to

startActivity(new Intent (this, MainActivity.class));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM