2012-04-01 56 views
0

我有我的代碼設置爲單擊getFin按鈕時,標題爲getfinal的xml佈局。但是,只要我點擊那個按鈕,我的應用程序就會崩潰。 setContentview是否在這種情況下使用了錯誤的命令?如果是這樣,我怎樣才能去點擊按鈕上的新的XML佈局?如何使用On Click Listener轉到不同的xml佈局?

package wilson.GC; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.view.View; 
import android.view.View.OnClickListener; 

public class GradeCalculatorActivity extends Activity { 
/** Called when the activity is first created. */ 
Button getEx, getFin; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    getEx = (Button)findViewById(R.id.getexambutton); 
    getFin = (Button)findViewById(R.id.getfinalbutton); 
    getFin.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      setContentView(R.layout.getfinal); 
      double q1, q2, ex, fin; 
      EditText etq1, etq2, eteg; 
      etq1 = (EditText)findViewById(R.id.editText1); 
       q1 = Double.parseDouble(etq1.getText().toString()); 
      etq2 = (EditText)findViewById(R.id.editText2); 
       q2 = Double.parseDouble(etq2.getText().toString()); 
      eteg = (EditText)findViewById(R.id.editText3); 
       ex = Double.parseDouble(eteg.getText().toString()); 

      fin = 0.4*q1+0.4*q2+0.2*ex; 
       if(fin == (int)fin){ 
        System.out.println((int)fin); 
       } 
       else{ 
        fin = 0.01*((int)(fin*100)); 
        System.out.println(fin); 
       } 
      TextView tvfin = null; 
      tvfin.setText(fin+""); 
      tvfin = (TextView)findViewById(R.id.tvfinalgrade); 

     } 
    }); 
} 
} 

讓我知道你是否需要這兩個xml頁面的代碼。

+0

可以粘貼你的崩潰日誌 – Ishu 2012-04-01 14:50:14

回答

2

對於同一活動,您不能使用setContentView()兩次。您最好使用setContentView()來製作一個全新的Activity併爲其指定getFinal佈局。使用意圖打開按鈕的onClick()中的活動。

+0

謝謝,虐待試試吧! – Wilson 2012-04-01 14:54:48

2

將佈局getfinal.xml移動到駐留在main.xml中的ViewSwitcher中。在onClick中,只需使用ViewSwitchers showNext()方法切換佈局。

佈局文件可能看起來像這樣(sudo代碼)。

<ViewSwitcher android="@+id/switcher> 
    <LinearLayout android:id="@+id/first_layout"> ... first content with button ... </LinearLayout> 
    <LinearLayout android:id="@+id/second_layout"> ... content to show when pressed... </LinearLayout> 
</ViewSwitcher> 

然後做:

setContentView(R.layout.main); 
    getEx = (Button)findViewById(R.id.getexambutton); 
    switch = (ViewSwitcher) findViewById(R.id.switcher); 
    getFin = (Button)findViewById(R.id.getfinalbutton); 
    getFin.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) { 
     switch.showNext(); 
     ..... 
    });