如何在自定义适配器中的按钮单击事件上启动新活动?

时间:2015-03-13 07:11:28

标签: android

我是Android的新手,仅使用google执行代码,PLZ帮助。

这是来自自定义适配器的代码,用于具有文本和按钮列表的自定义视图,在按钮点击事件上我想要开始新活动,例如,如果用户按下“前面的按钮”几何“文本,然后新活动应该开始,我应该在上面的代码中传递什么:

     @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;
   }

3 个答案:

答案 0 :(得分:3)

intent赞成

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

请记住,您必须在secondActivity

中注册manifest.xml

你也应该改变

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

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

始终使用。equals()方法进行string比较。

答案 1 :(得分:1)

- 将上下文从活动传递到适配器就像 Youadapter obj = new Youradapter(Youactivity.this); - 在你的适配器类中设置Context con; - 并使用con.startactivity;

答案 2 :(得分:0)

  

如何在自定义适配器中的按钮点击事件上启动新活动?

首先,使用String.equals来比较字符串:

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

第二个,使用字符串类名启动Activity使用Class.forName来获取类:

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

并确保所有活动都在AndroidManifest.xml

中声明

注意:如果txtListChild.getText()返回活动名称,则无需使用if-else只需使用Class.forName获取类并将其作为Intent构造函数的最后一个参数传递: