2012-12-19 2 views
1

하나의 버튼을 클릭하면 동적으로 버튼을 만들고 있습니다. 즉 해당 버튼의 onClick 이벤트에서 발생합니다. 그러나 버튼을 클릭 할 때마다 n 개의 버튼을 동적으로 생성하여 하나의 버튼이 생성됩니다.클릭 이벤트로 안드로이드에 프로그래밍 방식으로 버튼 만들기

LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1); 
..... 

public void onClick(View arg0) { 
Button topArtistbutton = new Button(SalesPanel.this, null,android.R.attr.buttonStyleSmall); 
topArtistbutton.setText("Top Artist"); 
topArtistbutton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));topArtistbutton.setId(3); 
ll.addView(topArtistbutton); 
} 

내가 단 하나 개의 버튼을 동적으로

답변

5
boolean bCreate = true; 
... 
public void onClick(View arg0) { 
    if (bCreate) 
    { 
     Button topArtistbutton = new Button(SalesPanel.this, null,android.R.attr.buttonStyleSmall); 
     topArtistbutton.setText("Top Artist"); 
     topArtistbutton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));topArtistbutton.setId(3); 
     ll.addView(topArtistbutton); 
     bCreate = false; 
    } 
} 
+0

좋은 캐치 .... :) –

1

만든 플래그를 설정하고 버튼을 이미 생성 여부 확인 if 문을 사용하려면 :

boolean created = false; 


public void onClick(View arg0) { 
if (!created) { 

    Button topArtistbutton = new Button(SalesPanel.this, null,android.R.attr.buttonStyleSmall); 
    topArtistbutton.setText("Top Artist"); 
    topArtistbutton.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)); 
    topArtistbutton.setId(3); 
    ll.addView(topArtistbutton); 
    created = true; 
    } 
} 
관련 문제