2014-10-31 117 views
0

我已經顯示了一個動態創建的10鍵佈局,現在我需要檢索按鈕的ID以釋放必要的過程。這裏的代碼。動態按鈕Android

Button Btn; 
Toast msg; 
RelativeLayout rl; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.setContentView(R.layout.main); 

    LinearLayout ll = (LinearLayout) findViewById(R.id.ll); 
    Btn = (Button) findViewById(R.id.Btntu); 

    for (int i = 0; i < 10; i++) { 
     Btn = new Button(this); 
     Btn.setText("Número: " + i); 
     Btn.setGravity(Gravity.CENTER); 
     Btn.setId(i); 

     rl = new RelativeLayout(this); 

     RelativeLayout.LayoutParams parametros = new RelativeLayout.LayoutParams(
     LayoutParams.WRAP_CONTENT, 
     LayoutParams.WRAP_CONTENT); 

     Btn.setLayoutParams(parametros); 

     rl.setLayoutParams(new LayoutParams(      
          LayoutParams.FILL_PARENT, 
          LayoutParams.WRAP_CONTENT) 
          ); 

     rl.addView(Btn); 
     ll.addView(rl); 
    } 

我需要的功能來檢索按鈕的ID。 謝謝大家。 :o)

回答

0

你試過getId()

http://developer.android.com/reference/android/view/View.html#getId%28%29

for (int i = 0; i < 10; i++) { 
     Btn = new Button(this); 
     Btn.setText("Número: " + i); 
     Btn.setGravity(Gravity.CENTER); 
     Btn.setId(i); 
     Btn.setOnClickListener(new OnClickListener() { 
      public void onClick(View v) 
      { 
       Log.d("Button", "ID clicked: " + Btn.getId()); 
       // Or even 
       Log.d("View", "ID clicked: " + v.getId()); 
      } 
     }); 
     (...) 
}