简体   繁体   中英

How can I start new Activity based on the item clicked in listview?

I have been stuck on this for 2 days now, I don't see why the below code is not working, the problem seems to be the "if" block on the onItemClick, please I'lld really appreciate if anyone can help me out with this. Thanks.

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = parent.getItemAtPosition(position).toString();
                Toast.makeText(SearchActivity.this, name,Toast.LENGTH_LONG).show();
                if (name=="Sweet Tooth"){
                    Intent intent = new Intent(SearchActivity.this,SwitActivity.class);
                    startActivity(intent);
                }
            }
        });

Try this:

String name = listview.getItemAtPosition(position).toString();

And

if (name.equals("Sweet Tooth")){
                    Intent intent = new Intent(SearchActivity.this,SwitActivity.class);
                    startActivity(intent);
                }

in java String == String will always return false.

use this instead.

String s = "Sweet Tooth";

if (s.equals("Sweet Tooth"){
   //code
}

In Java, you compare two Strings by using equals function.

String name = parent.getItemAtPosition(position).toString();
if (name.equals("Sweet Tooth")){
    startActivity(new Intent(SearchActivity.this,SwitActivity.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