使用onClickListener进行Android启动活动? [英] Android start activity with onClickListener?

查看:104
本文介绍了使用onClickListener进行Android启动活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行家庭更换申请。我正在尝试将 OnClickListener 添加到带有Java的按钮,但我正在尝试的方式产生错误:

I'm working on a home replacement application. I'm trying to add an OnClickListener to a button with Java but the way I'm trying produces error:


方法startActivity(Intent)未定义类型new View.OnClickListener(){}

The method startActivity(Intent) is undefined for the type new View.OnClickListener(){}

此代码位于适配器 MyPagerAdapter 内。

这就是我正在尝试的:

    buttonItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent("com.android.contacts.ContactsApplication");
            startActivity(intent);
        }
    });

如何将 OnClickListener 添加到a打开另一个应用程序的按钮,例如 com.android.contacts.ContactApplication

How can I add an OnClickListener to a button that opens another application, like for example com.android.contacts.ContactApplication?

编辑:
这是完整的代码,我现在正在尝试:

This is the full code, with what I am trying right now:

public class MyPagerAdapter extends PagerAdapter {

    @Override
    public Object instantiateItem(View container, int position) {
        Context context = container.getContext();
        LinearLayout layout = new LinearLayout(context);
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        TextView textItem = new TextView(context);
        Button buttonItem = new Button(context);
        buttonItem.setText("Aceptar");

        // This is what I'm trying, (crashes on click)
        buttonItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.android.contacts.ContactsApplication");
               v.getContext().startActivity(intent); 
            }
        });


推荐答案

 buttonItem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i = new Intent();
        i.setComponent(new ComponentName("com.android.contacts", "com.android.contacts.DialtactsContactsEntryActivity"));
        i.setAction("android.intent.action.MAIN");
        i.addCategory("android.intent.category.LAUNCHER");
        i.addCategory("android.intent.category.DEFAULT");
        v.getContext().startActivity(i);
    }

这篇关于使用onClickListener进行Android启动活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆