简体   繁体   中英

How to start new activity on button click event in custom adapter?

I am very new in Android, doing code using google only, plz help.

Here is my code from custom adapter, which is for custom view which is having list of text and buttons, on button click event i want to start new activity, like for example, if user press button which is in front of "Geometry" text, then new activity should get start, what should I pass to intent in above code:

     @Override
     public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) {

         btn.setOnClickListener(new View.OnClickListener()
                {
                     @Override
                     public void onClick(View v)
                     {
                         if(txtListChild.getText().toString()=="Geometry")
                         {
                             Toast.makeText(_context,   txtListChild.getText().toString(),
                                     Toast.LENGTH_LONG).show();
                             **Intent i=new Intent();**
                             _context.startActivity(i);
                         }

                     }
                });

     return convertView;
   }

Make intent like

  Intent i=new Intent(_context,secondActivity.class);
  _context.startActivity(i);

Remember you must register secondActivity in manifest.xml

and also you should change

 if(txtListChild.getText().toString()=="Geometry")

to

 if(txtListChild.getText().toString().equals("Geometry"))

always used . equals() method for string comparison.

-By passing context from activity to the adapter like Youadapter obj=new Youradapter (Youactivity.this); -In you adapter class set you Context con; -and using con.startactivity;

How to start new activity on button click event in custom adapter?

First, use String.equals for comparing strings:

if(txtListChild.getText().toString().equals("Geometry"))

Second , to start Activity using string class name use Class.forName to get class:

Class<?> c = Class.forName(txtListChild.getText().toString());
Intent i=new Intent(v.getContext(),c);

And make sure all activities are declared in AndroidManifest.xml

NOTE: if txtListChild.getText() return Activity name then no need to use if-else just use Class.forName to get class and pass it as last parameter of Intent constructor :

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