2014-10-01 75 views
0

我正在爲一個項目製作一個簡單的GPA計算器,我們先用xml做了它,現在我的教授動態地要求它。我有4個textview,4個edittext和1個按鈕。一切工作正常,並運行,但是當我嘗試setOnClickListener()程序將崩潰。我怎樣才能使按鈕以編程方式工作。 這是我正在嘗試。setOnClickListener to a Programmatically ERROR

 android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    LinearLayout layout = new LinearLayout(this); 
    layout.setOrientation(LinearLayout.VERTICAL); 

    // button 
    Button button1 = new Button(this); 
    final int button1id = View.generateViewId(); 
    button1.setId(button1id); // id 
    button1.setText("Send Data"); 
    button1.setLayoutParams(params); 
    layout.addView(button1); 
    button1 = (Button) findViewById(button1id); 

    OnClickListener clicks = new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if(v.getId() == button1id){ 
       Intent i = new Intent(getApplicationContext(), SecondActivity.class); 
       startActivity(i); 

      } 

     } 
    }; 

然後當我打電話給它,它給了我錯誤。

button1.setOnClickListener(clicks); 

在此先感謝。

+1

你能後你得到錯誤信息? – 2014-10-01 17:54:25

回答

4

不要做findViewById。只是簡單的電話:

button1.setOnclickListner(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 

       Intent i = new Intent(getApplicationContext(), SecondActivity.class); 
       startActivity(i); 
     } 
    }); 

這將解決您的問題。

0

沒有必要再調用由ID按鈕也更改View.OnClickListener只是OnClickListener

android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    LinearLayout layout = new LinearLayout(this); 
    layout.setOrientation(LinearLayout.VERTICAL); 

    // button 
    Button button1 = new Button(this); 
    final int button1id = View.generateViewId(); 
    button1.setId(button1id); // id 
    button1.setText("Send Data"); 
    button1.setLayoutParams(params); 
    layout.addView(button1); 
    button1.setOnClickListener(clicks) 

    OnClickListener clicks = new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if(v.getId() == button1id){ 
       Intent i = new Intent(getApplicationContext(), SecondActivity.class); 
       startActivity(i); 

      } 

     } 
    };