0

我在android中編程,並向我介紹問題 private Button botonN [] = new Button [10]; 如何初始化? botonN [0] =(Button)findViewById(R.id.boton0); 這不能 他們解決android如何初始化botonN []

CODE

public class Facil extends Activity implements View.OnClickListener{ 
private Button botonN[]=new Button[10] ; 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.facil); 
    for (int i = 0; i < botonN.length;botonN[i++].setOnClickListener(this)); 
    botonN [0]=(Button) findViewById(R.id.boton0); 
    botonN [1]=(Button) findViewById(R.id.boton1); 
    botonN [2]=(Button) findViewById(R.id.boton2); 
    botonN [3]=(Button) findViewById(R.id.boton3); 
    botonN [4]=(Button) findViewById(R.id.boton4); 
    botonN [5]=(Button) findViewById(R.id.boton5); 
    botonN [6]=(Button) findViewById(R.id.boton6); 
    botonN [7]=(Button) findViewById(R.id.boton7); 
    botonN [8]=(Button) findViewById(R.id.boton8); 
    botonN [9]=(Button) findViewById(R.id.boton9); 


    } } 

<ImageButton 
android:layout_width="40dp" 
android:layout_height="40dp" 
android:id="@+id/boton0" 
android:layout_marginTop="10dp" 
android:layout_below="@+id/imageButton" 
android:layout_alignParentLeft="true" 
android:layout_alignParentStart="true" 
android:background="@drawable/botonamarillo0" 
android:layout_marginLeft="20dp" /> 
+0

是按鈕動態添加還是從XML? – MilapTank

+0

我需要初始化findViewById(R.id。);只有 – user3800023

+0

比你必須設置ID還仍然我很困惑你想做什麼PLZ說更多 – MilapTank

回答

0

嘗試添加按鈕,這樣的(它的樣品):

List<Button> botonN = new ArrayList<Button>(); 

     for (int i = 0; i < botonN.size(); i++){ 
     botonN.add((Button) findViewById(R.id.boton0); 
     botonN.add((Button) findViewById(R.id.boton1); 
     botonN.add((Button) findViewById(R.id.boton2); 
//Add more button 
    } 

這之後,您可以設置的onclick監聽你的按鈕。

編輯 試試這個太:

for (int index = 0; index < botonN.size(); index++) { 
      botonN.get(index).setOnClickListener(new OnClickListener() { 

       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 

       } 
      }); 
     } 

也許會有所幫助。

+0

無法解析方法添加 – user3800023

+0

對不起不知道如何添加設置onclick監聽按鈕 是否等於? – user3800023

+0

您的「無法解決方法添加」問題解決了嗎? – Amsheer