5

我正在开发一个家庭更换应用程序。我正在尝试OnClickListener使用 Java 添加一个按钮,但我尝试的方式会产生错误:

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

此代码在适配器内MyPagerAdapter

这就是我正在尝试的:

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

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


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

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); 
            }
        });
4

2 回答 2

9
 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);
    }
于 2013-01-10T20:43:24.477 回答
1
(findViewById(R.id.button)).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        startActivity(new Intent(v.getContext(), ACTIVITY.class));
    }
});
于 2016-01-23T17:44:26.397 回答