如何在主.java文件中添加另一个侦听器

时间:2013-09-08 22:05:56

标签: android button project listener add

当我在(主要活动.x m l)中添加另一个按钮(nextButton2)时! 现在我想让按钮打开(第三个屏幕.x m l)

你可以帮助我在(main.java)的这个android项目中添加监听器但是失败了吗?

link original project

my project link

2 个答案:

答案 0 :(得分:0)

有很多方法可以实现这一目标:

匿名听众

如果只需要听众一次:

public class Main extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        button1.setOnClickListener(new OnClickListener() {
            // your first listener here
        });
        button2.setOnClickListener(new OnClickListener() {
            // your second listener here
        });
    }
}

多个嵌套类

如果要在同一个类中重复使用侦听器:

public class Main extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        button1.setOnClickListener(new Listener1());
        button2.setOnClickListener(new Listener2());
    }

    class Listener1 implements OnClickListener {
        // your first listener here
    }

    class Listener2 implements OnClickListener {
        // your second listener here
    }
}

多个顶级课程

如果要在多个类中重复使用侦听器:

public class Main extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        button1.setOnClickListener(new Listener1());
        button2.setOnClickListener(new Listener2());
    }
}

class Listener1 implements OnClickListener {
    // your first listener here
}

class Listener2 implements OnClickListener {
    // your second listener here
}

答案 1 :(得分:0)

然后是代码中的现有逻辑,它的外观如下:

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.nextButton).setOnClickListener(new handleButton());
        findViewById(R.id.nextButton2).setOnClickListener(new handleButton2());
    }
    class handleButton implements OnClickListener {
        public void onClick(View v) {
            Intent intent = new Intent(Main.this, Screen2.class);
            startActivity(intent);  
        }
    }

    class handleButton2 implements OnClickListener {
        public void onClick(View v) {
            Intent intent = new Intent(Main.this, Screen3.class);
            startActivity(intent);  
        }
    }
}

它假定您已经创建了名为Screen3.java的新活动并将其添加到清单文件中:

<activity android:name="your.project.package.Screen3" android:label="@string/app_name" />