2014-08-29 43 views
-2

我想同时从另一个类打开该类和该类的方法。当我点击按钮时,它会停止应用程序。帮帮我!类的固定装置“从中我想调用类的如何启动一个活动并使用另一个类调用该类的方法

方法和手段的

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; 
    } 
} 
} 
+0

是你可以做..让公共无效的xyz(){} ..完蛋了..是你在寻找什么? – Elltz 2014-08-29 18:38:49

+0

使它公开没有更好。我认为问题在于当我调用方法时,我还没有创建Intent,所以它不是指fixturedetails.xml文件,因此不设置文本。 – Anuj 2014-08-29 18:44:53

回答

0

由于Android处理活动类的生命周期不建议直接实例化,并且像你一样调用该方法,Android会重新创建类,无论如何会破坏您在其中更改的任何内容。

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

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; 
     } 
    } 
} 
+0

它的工作,非常感谢!我被困在这一点上好几天了...... – Anuj 2014-08-30 05:27:53