0

我有一个要分配给的按钮OnClickListener。因此,我想开始一个新的意图。为此,我必须参考活动。我唯一知道如何做到这一点的是通过以下代码。这是从按钮单击开始意图的最佳方式吗?此外,这会产生什么样的记忆影响?

public class SomeActivity extends FragmentActivity  {

    private final FragmentActivity self=this;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        findViewById(R.id.startButton).setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                Intent intent=new Intent(self,someClass.class);
                startActivity(intent);
            }
        });

}
4

2 回答 2

1

最好的方法是简单地通过ActtivityName.this,如下所示:

public class SomeActivity extends FragmentActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        findViewById(R.id.startButton).setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                Intent intent=new Intent(SomeActivity.this,someClass.class);
                startActivity(intent);
            }
        });

}
于 2012-11-22T00:19:00.623 回答
0

Another way to do this will be calling :
findViewById(R.id.startButton).setOnClickListener(this);
Then make your Activity implement View.OnClickListener and implement the methods onClick(View v) in this way :

public void onClick(View v) {
    switch(v.getId()) {
        case R.id.startButton:
            Intent intent=new Intent(self,someClass.class);
            startActivity(intent);
            break;

        // Handle click on other views

    }
}

It prevents from instantiating a listener and should be a bit better for memory consumption.

于 2012-11-21T22:17:37.300 回答