如何在几个动态创建的微调器上setOnItemSelectedListener

时间:2016-12-12 19:46:09

标签: android android-linearlayout android-spinner

我有一个Activity,我需要根据外部数据库动态创建一个或多个微调器。

此微调器项目的SOY必须根据微调器具有的值显示对话框。例如,微调器有以下选项: -拥有 -Rental -家庭住宅 如果用户选择租赁,我必须显示一个对话框(或任何内容),询问他每月支付多少钱。如果他选择自己或家庭,就不会发生任何事情。

使用微调器,edittexts等创建布局后,我使用类似这样的东西:

for(int q=0;q<=parent.getChildCount();q++){

        View v = parent.getChildAt(q);
        if (v instanceof Spinner) {
            Spinner res = (Spinner) v;
            res.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                    //Here its supposed to show dialog if the option is "RENT"
                }

                public void onNothingSelected(AdapterView<?> adapterView) {
                    return;
                }
            });
        }
    }

问题在于,当我这样做时,&#34; setOnItemSelectedListener&#34;仅设置布局上的最后一个微调器。

我怎样才能做我想做的事情?我不知道还能做什么。

1 个答案:

答案 0 :(得分:0)

最简单的解决方案可能是将一个Listener作为变量,并将其用于所有的微调器。要做到这一点,你不会像现在这样设置它(使用匿名的内部类样式),而是这样做:

//This goes outside of the method
private AdapterView.OnItemSelectedListener listener = 
        new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        System.out.println("Spinner Selected ID = " + parent.getId());
        /*
        Put a check here for which one is being selected.
        While you could use the parent to check, in your case, it will be easier
        to use something from your DB table as a unique identifier (maybe a column
        name would be ideal? Your pick)
         */
        //Show your dialogs here
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        return;
    }
};

//This is the method you have where you are iterating the parent object
private void doStuff(){
    for(int q=0;q<=parent.getChildCount();q++){
        View v = parent.getChildAt(q);
        if (v instanceof Spinner) {
            Spinner res = (Spinner) v;
            res.setOnItemSelectedListener(listener);
        }
    }
}

祝你好运!

相关问题