如何为多个AutoCompleteTextView设置相同的属性?

时间:2014-09-19 18:25:18

标签: android

鉴于我有以下AutoCompleteTextViews

    ArrayAdapter<String> adapter121 = new ArrayAdapter<String>    
    (this,android.R.layout.simple_dropdown_item_1line,androidBooks);
    AutoCompleteTextView acTextView = (AutoCompleteTextView)findViewById(R.id.AndroidBooks);
    AutoCompleteTextView acTextView0 = (AutoCompleteTextView)findViewById(R.id.AndroidBooks1);
    AutoCompleteTextView acTextView1 = (AutoCompleteTextView)findViewById(R.id.et3);
    AutoCompleteTextView acTextView2 = (AutoCompleteTextView)findViewById(R.id.et4);
    AutoCompleteTextView acTextView3 = (AutoCompleteTextView)findViewById(R.id.et5);
    AutoCompleteTextView acTextView4 = (AutoCompleteTextView)findViewById(R.id.et6);
    AutoCompleteTextView acTextView5 = (AutoCompleteTextView)findViewById(R.id.et7);
    AutoCompleteTextView acTextView6 = (AutoCompleteTextView)findViewById(R.id.et8);
    AutoCompleteTextView acTextView7 = (AutoCompleteTextView)findViewById(R.id.et9);

我该怎么称呼:

    acTextView.setThreshold(1);
    acTextView.setAdapter(adapter121);

在我的每个AutoCompleteTextViews上?

2 个答案:

答案 0 :(得分:1)

要设置每个AutoCompleteTextViews,您可以为它们添加一个数组mAutoCompleteTextViews,并通过循环遍历每个属性来设置属性。

ArrayAdapter<String> adapter121 = new ArrayAdapter<String>
                (this,android.R.layout.simple_dropdown_item_1line,androidBooks);

        AutoCompleteTextView[] mAutoCompleteTextViews = new AutoCompleteTextView[{
        (AutoCompleteTextView)findViewById(R.id.AndroidBooks),
        (AutoCompleteTextView)findViewById(R.id.AndroidBooks1),
        (AutoCompleteTextView)findViewById(R.id.et3),
        (AutoCompleteTextView)findViewById(R.id.et4),
        (AutoCompleteTextView)findViewById(R.id.et5),
        (AutoCompleteTextView)findViewById(R.id.et6),
        (AutoCompleteTextView)findViewById(R.id.et7),
        (AutoCompleteTextView)findViewById(R.id.et8),
        (AutoCompleteTextView)findViewById(R.id.et9)}];

        // for each loop to set parameters on each AutoCompleteTextView in mAutoCompleteTextViews 
        for (AutoCompleteTextView acTextView : mAutoCompleteTextViews ){
            acTextView.setThreshold(1);
            acTextView.setAdapter(adapter121);
        }

如果您想了解Java中的数组,请查看Java wikibook中的this section

答案 1 :(得分:0)

您实际上可以创建一个为您完成所有这些操作的循环

int numberOfViews = 9;
for(int i = 0; i < numberOfViews; i++){
    AutoComplete acTextView;
    if(i == 0)
        acTextView = (AutoCompleteTextView)findViewById(R.id.AndroidBooks);
    if(i == 1)
        acTextView = (AutoCompleteTextView)findViewById(R.id.AndroidBooks1);
    else{
        int id = getResources().getIdentifier("et" + (i+1), "id", getPackageName());
        acTextView = (AutoCompleteTextView)findViewById(id);
    }
    acTextView.setThreshold(1);
    acTextView.setAdapter(adapter121);
}
相关问题