2014-08-29 42 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