2015-12-13 56 views
0

我在我的MainLayout.xml中有更多的100 button,我想處理每個點擊。我想分組所有的按鈕,然後聽取點擊組按鈕,獲取ID並將其放入String,然後將其用作我的基本ID從我的Sqlite Databse Table查詢。我怎樣才能做到這一點?到目前爲止,我在我的MainClass.java上有這個。Android識別多個按鈕

MainClass.java

public class MainClass extends AppCompatActivity implements View.OnClickListener { 
    Button B0,B1,B2,B3....; 
    String baseId; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main_layout); 

     buttonInitializer(); 
    } 

    public void buttonInitializer(){ 
     B0 = (Button)findViewById(R.id.B0); B0.setOnClickListener(this); 
     B1 = (Button)findViewById(R.id.B1); B1.setOnClickListener(this); 
     ... 
    } 

    @Override 
    public void onClick(View v) { 
     switch (v.getId()){ 
      case R.id.B0: 
       baseId = "B0"; 
       break; 
      case R.id.B1: 
       baseId = "B1"; 
       break; 
      .......... 
      default: 
       break; 
     } 
     QueryFire(); // Fire a query 
    } 

    Public void QueryFire(){ 
     //Fire the query with id of the clicked button 
    } 
} 

正如你可以看到,如果我繼續這樣做,我會很早就代碼,我想縮短我的代碼,而不是上面的代碼,我想分組按鈕,然後聽每個點擊就像RadioButton,但注意。我不想使用RadioButton。我試圖實現這個seudo代碼。

// Put the button into RelativeLayout or something and use it to group the button 
// OnClick of Each Button inside the GroupButton: 
    // Get the ID of the Clicked Button: 
    // Put the ID of Button into String: 
    // and FIRE my query with ID of Button 

任何幫助,不勝感激!非常感謝你!!!

回答

0

可能會有一點延伸,但爲什麼不使用帶有自定義適配器的ListView?每個適配器將保存一個按鈕(或任何你想要的),並且每當點擊按鈕時,你將得到id(單擊元素的位置)。它更容易在內存:)

1

你應該能夠爲你的xml佈局中的每個按鈕的「android:tag」屬性以及「android:onclick」屬性指定一個字符串。這應該消除對所有findViewById()和setOnClickListener()調用的需要。

然後,在您的onClick方法中,您可以執行如下操作:baseId = (String) view.getTag()