2012-09-28 23 views
0

我的佈局有4個按鈕。一個是「正確的」答案,另外三個是「錯誤的」答案。 我想與被壓3「錯」的一個按鈕來顯示相同​​的彈出窗口。這是我得到的代碼。調用一個方法多次 - Android的代碼

我不想重複此代碼爲每個3個按鈕的,我怎麼叫有不同的按鈕名稱相同的代碼?

ImageButton rredButton=(ImageButton)findViewById(R.id.RredButton); 
    rredButton.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      LayoutInflater layoutInflater 
      = (LayoutInflater)getBaseContext()  
      .getSystemService(LAYOUT_INFLATER_SERVICE); 
      View popupView = layoutInflater.inflate(R.layout.popupright, null); 
      final PopupWindow popupWindow = new PopupWindow(    
        popupView,     
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT);        

      Button btnDismiss = (Button)popupView.findViewById(R.id.nextscreen);    
      btnDismiss.setOnClickListener(new Button.OnClickListener(){  
       @Override  
       public void onClick(View v) {  
        Intent myintent1 = new Intent(colorActivity.this,LearningTimeMenu.class); 
        startActivity(myintent1); 
       } 
      }); 
     }}); 

回答

2

試試這個

private void createPopUP() 
{ 
    LayoutInflater layoutInflater 
      = (LayoutInflater)getBaseContext()  
      .getSystemService(LAYOUT_INFLATER_SERVICE); 
      View popupView = layoutInflater.inflate(R.layout.popupright, null); 
      final PopupWindow popupWindow = new PopupWindow(    
        popupView,     
        LayoutParams.WRAP_CONTENT,      
        LayoutParams.WRAP_CONTENT);        

      Button btnDismiss = (Button)popupView.findViewById(R.id.nextscreen);    
      btnDismiss.setOnClickListener(new Button.OnClickListener(){  
       @Override  
       public void onClick(View v) {  
        Intent myintent1 = new Intent(colorActivity.this,LearningTimeMenu.class); 
        startActivity(myintent1); 
       } 
      }); 

} 

ImageButton rredButton=(ImageButton)findViewById(R.id.RredButton); 
rredButton.setOnClickListener(new View.OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 

     createPopUP(); 

    }}); 

否則,在XML文件中,使用

<Button .......... 
android: onClick ="createPopUP" 
</Button> 
+0

謝謝。這工作。是否有任何特別的理由使用「私人」無效與「保護」無效? – Jasma