6

我正在尝试从自定义 onclick 侦听器开始一个新活动。但它无法从 onclick 监听器访问 MainActivity 实例。此外,它显示错误的意图构造函数。这是我的代码:

public class ChartClickListener implements OnClickListener {
    private String ChartLink;
    public ChartClickListener(String chartLink){
        this.ChartLink=chartLink;
    }
    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        Intent intent=new Intent(MainActivity.this,ChartImageActivity.class);
        intent.putExtra("chartLink", ChartLink);
        startActivity(intent);
    }
}

我在这里先向您的帮助表示感谢。

4

5 回答 5

28

将您的代码修改为:

@Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        Intent intent=new Intent(view.getContext(),ChartImageActivity.class);
        intent.putExtra("chartLink", ChartLink);
        startActivity(intent);
    }
于 2013-10-19T08:38:38.710 回答
7

试试这样

@Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        Intent intent=new Intent(view.getContext(),ChartImageActivity.class);
        intent.putExtra("chartLink", ChartLink);
        view.getContext().startActivity(intent);//Changed Here
    }

希望它会起作用

于 2013-10-19T08:42:59.093 回答
4

将活动上下文传递给自定义 onclick 侦听器并使用该上下文启动活动

 public class ChartClickListener implements OnClickListener {
    private String ChartLink;
    Context c;
    public ChartClickListener(String chartLink,Context context){
        this.ChartLink=chartLink;
        this.c=context;
    }
    @Override
    public void onClick(View view) {
        // TODO Auto-generated method stub
        Intent intent=new Intent(c,ChartImageActivity.class);
        intent.putExtra("chartLink", ChartLink);
        c.startActivity(intent);
    }

}

将 setOnClickListener 设置为

ChartClickListener chartclicklistener=new ChartClickListener("chartLink",MainActivity.this);
b.setOnClickListener(chartclicklistener);
于 2013-10-19T09:17:57.860 回答
2

替换MainActivity.thisview.getContext(),它将起作用。

于 2013-10-19T09:04:12.917 回答
0

我试试这个,它工作,我想展示一个 Toast,然后转移到一个新的 Activity。

public class NumbersClickListener implements View.OnClickListener {

@Override
public void onClick(View view){
    Toast.makeText(view.getContext(),"Open the list of Numbers",Toast.LENGTH_SHORT).show();
    switch (view.getId()){
        case R.id.numbers:
            Intent i  = new Intent(view.getContext(), NumberActivity.class);
            view.getContext().startActivity(i);
            break;
        case R.id.family:
            Intent   i2  = new Intent(view.getContext(),FamilyActivity.class);
            view.getContext().startActivity(i2);
            break;
        case R.id.colors:
            Intent  i3  = new Intent(view.getContext(),ColorsActivity.class);
            view.getContext().startActivity(i3);
            break;
        case R.id.phrases:
            Intent  i4  = new Intent(view.getContext(),PhrasesActivity.class);
            view.getContext().startActivity(i4);
            break;

    }

}

}

于 2018-03-27T01:49:37.317 回答