簡體   English   中英

獲取以編程方式創建的微調框的位置

[英]get position of spinner that was created programmatically

用戶在EditText輸入數字,然后應用程序以編程方式創建許多微調器。 當用戶單擊我的UI底部的“保存”按鈕時,我在獲取這些微調器的位置以保存它們時遇到問題。

當我嘗試使用以下方法獲取位置時: mArraySpinner.add(spinner.getSelectedItemPosition()); 如下所示,我在數組中有幾個空位置,就像偵聽器在創建時觸發一樣,然后它只會將最后一個微調器位置保存在數組的最后一個元素中。

這是我用來創建微調器的代碼:

for(int i = 1; i <= numStockTanks; i++) {
        TableRow tR = new TableRow(this);
        // creates the textView
        tV1 = new TextView(this);
        tV1.setText("Stock Tank #" + i + " size: ");

        // add spinner to row
        spinner = new Spinner(this);
        ArrayAdapter<CharSequence> adapterStockTankSize = ArrayAdapter.createFromResource(
                this, R.array.StockTankSize, android.R.layout.simple_spinner_item);
        adapterStockTankSize.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapterStockTankSize);
        spinner.setTag(i + 600);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onNothingSelected(AdapterView<?> parent) {}
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                mArraySpinner.add(spinner.getSelectedItemPosition());
            }
        });

        // add the TextView and the editText to the new TableRow
        tR.addView(tV1);
        tR.addView(spinner);

        // add the TableRow to the TableLayout
        tL.addView(tR,new TableLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));    
    } // end for statement

謝謝你的幫助

您每次都在重新指定spinner變量,但是onItemSelected方法正在使用此變量。 您每次都需要重新聲明此Spinner變量,以便該方法尋找唯一的Spinner對象。

更改spinner = new Spinner(this); final Spinner spinner = new Spinner(this); ,並刪除您已經擁有的任何spinner聲明。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM