如何使用另一个类启动Activity并调用该类的方法

时间:2014-08-29 18:20:41

标签: android method-call

我想同时从另一个类打开该类和该类的方法。当我点击按钮时,它会停止应用程序。救命啊!

类'Fixtures'的方法,我想从中调用class和Method

public void onClick(View arg0) {
    // TODO Auto-generated method stub

    int id = arg0.getId();
    FixtureDetails abc = new FixtureDetails();
    abc.xyz(id);
    startActivity(new Intent(Fixtures.this, FixtureDetails.class));
}

我想要打开的类和方法

public class FixtureDetails extends Activity{

TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fixturedetails);
    tv = (TextView) findViewById(R.id.tv);
}

void xyz(int lmn)
{
    switch(lmn)
    {
    case R.id.tvMatch1:
        tv.setText("Hey there, wassup");
        break;
    }
}
}

1 个答案:

答案 0 :(得分:0)

因为Android处理Activity类的生命周期,所以不建议直接实例化它,并且像Android一样调用该方法将重新创建该类,无论如何都会破坏你在其中更改的任何内容。

推荐的做法是使用Intent Extras将数据传递给您的活动。

public void onClick(View arg0) {
    // TODO Auto-generated method stub

    int id = arg0.getId();
    Intent intent = new Intent(Fixtures.this, FixturesDetails.class);
    intent.putExtra("id_key", id); // Set your ID as a Intent Extra
    startActivity(intent);
}

FixtureDetails.class

public class FixtureDetails extends Activity{

    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fixturedetails);
        tv = (TextView) findViewById(R.id.tv);
        Intent intent = getIntent();
        if(intent != null && intent.getExtras() != null) {
            xyz(intent.getIntExtra("id_key", -1)); // Run the method with the ID Value
                                                   // passed through the Intent Extra
        }
    }

    void xyz(int lmn) {
        switch(lmn) {
            case R.id.tvMatch1:
                tv.setText("Hey there, wassup");
                break;
        }
    }
}