【问题标题】:Unable to set spinner adapter on onItemSelected of first spinner无法在第一个微调器的 onItemSelected 上设置微调器适配器
【发布时间】:2016-05-20 11:32:40
【问题描述】:

我有两个微调器,比如类别和子类别。 OnItemSelected 的类别微调器我需要为 sub_categories 微调器设置适配器。我能够为类别设置微调器。但是 sub_categories 微调器正在制造麻烦。

这些数组列表来自服务器,我将其设为静态。 查看我的代码会给你正确的想法,我错了。

这是我的分类列表:

public static ArrayList<String> categories=new ArrayList<String>();
public static ArrayAdapter<String> mArryAdtSpnnr;

在 response.success 中,我正在尝试执行以下操作:

 for(int i=0;i<mArray.length;i++){categories.add(mArray[i].getName());}

在这个活动中,我需要 2 个微调器:

  private void initializeWidgets() {
        mspinner_categories=(Spinner)findViewById(R.id.spinner_categories);
        mspinner_categories.setOnItemSelectedListener(this);
        mspinner_subcategories=(Spinner)findViewById(R.id.spinner_subcategories);

        ProfessionalListActivity.mArryAdtSpnnr = new ArrayAdapter<String>( EditProfileActivity.this,
                android.R.layout.simple_spinner_item,ProfessionalListActivity.categories);

        mspinner_categories.setAdapter(ProfessionalListActivity.mArryAdtSpnnr);    
    }

并在其选定的项目上:

 @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String item = parent.getItemAtPosition(position).toString();
        Toast.makeText(EditProfileActivity.this,"Selected Item is: "+item,Toast.LENGTH_LONG).show();
       // mspinner_subcategories.setSelection(position);
        SubListProActivity.mArrySpnnr=new ArrayAdapter<String>
                    (EditProfileActivity.this,android.R.layout.simple_spinner_item,
                            SubListProActivity.subcategories);
        mspinner_subcategories.setAdapter(SubListProActivity.mArrySpnnr);
    }

我在点击第一个微调器时设置第二个微调器适配器。但是这个微调器上没有显示任何内容。我做了与其他活动类似的代码。 我很困惑,这可能是因为在 ProfessionalListActivity 我也得到了一个 category_id,以便打开相应的子列表。但在微调器中,我直接添加它。 编辑: 子列表类:

public static ArrayList<String> subcategories=new ArrayList<String>();
    public static ArrayAdapter<String> mArrySpnnr;

在其response.success中

for(int i=0;i<mArray.length;i++){
    subcategories.add(mArray[i].getName());
}

请帮忙

【问题讨论】:

  • SubListProActivity.subcategories哪里添加数据?
  • 您从未将subCategory 列表添加到列表中。你怎么能猜到结果。
  • 什么麻烦?我有一个可行的解决方案,但我需要更准确地了解正在发生的事情。如果可能,请提供屏幕截图(andropid studio 和 eclipse 允许您拍摄屏幕截图):)
  • @tonygil onitemselected 的第一个微调器,我希望我的第二个微调器存在并包含相应的列表。但是第二个微调器显示为空白
  • @tonygil 你能帮忙吗

标签: android retrofit android-spinner


【解决方案1】:

此代码将您的问题作为ExpandableList 处理,并且来自工作应用程序。首先是一个按钮的监听器,它调用以下活动:

  1. 显示可点击的第一级选项列表,激活后,
  2. 激活时显示可点击的二级选项的下拉列表
  3. 显示 3 个选项单选按钮组(每个单选按钮组只有 1 个选定按钮)

最初的应用程序是一个(农业)检查系统 - 用户从问题组(第一级:昆虫、真菌、杂草)中选择正在发生的问题(第二级:昆虫[军队蠕虫、瓢虫、蚂蚁],真菌[茎腐病,锈病,霉菌],杂草[普通草,非洲草,牵牛花])。

对于每个选定的第二级选项,会弹出一个单选按钮组来选择问题的严重性,用户必须选择级别 1(默认)、2 或 3。

数据被存储以供其他地方使用。

调用显示专用于检查的布局的活动,发送将填充可扩展列表的数据。

private final OnClickListener btnDoneOnClick = new OnClickListener() {
    public void onClick(View v) {
      String input = areaName.getText().toString();
      // english version
      //String[] groupName = {"INSECTS", "WEEDS", "FUNGHI", "CLIMATE", "VARIOUS"};
      String[] groupName = {"INSETOS", "ERVAS INVASORAS", "FUNGOS", "CLIMA", "VARIOS"};
      String[][] childName = {  { "Cigarrinha","Falsa medideira","Lagarta cartucho","Lagarta rosca","Percevejo (geral)"},
                { "Argentino","Buva","Capim colchao","Carrapicho","Corda viola","Falso Argentino","Leiteiro","Picao","Tiguera Milho","Tiguera Soja"},
                { "Antracnose","Cercospora","DFC","Ferrugem"},
                { "Erosao","Geada","Granizo","Incendio","Inundacao","Raio","Seca","Vento" },
                { "Furto","Fuga","Picada cobra" }
            };

      Intent intent00 = new Intent(getApplicationContext(), com.xxx.yyy.zzz.AgrInspectActivity.class);
      intent00.putExtra("groupName", groupName);
      int maxLength = 0;
      for (int i=0;i<groupName.length;i++) {
          intent00.putExtra(groupName[i], childName[i]);
          maxLength = Math.max(childName[i].length, maxLength);
      }
      intent00.putExtra("arrayLength", maxLength);

      // count childrenRows and put values in ARRAY
      // to be used by CustomList to inflate layouts
      // with proper number of lines
      int[] countChild = new int[groupName.length];
      for (int j=0;j<groupName.length;j++) {
          countChild[j] = childName[j].length;
      }
      intent00.putExtra("countChild", countChild);
      startActivity(intent00);

    }
};

活动本身:

public class AgrInspectActivity extends Activity {
    ExpandableListAdapter mAdapter;
    LayoutInflater mInflater;

    int arrayLength;
    String[] groups;
    String[][] children;
    int[][] array_output_data;
    String[][] array_output_data_quantity;
    int[] countChild;

    public int[][] getArray_output_data() {
        return array_output_data;
    }
    public String[][] getArray_output_data_quantity() {
        return array_output_data_quantity;
    }
    int choice = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inspection);
        ExpandableListView list = (ExpandableListView) findViewById(R.id.expandableListView1);
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            groups = extras.getStringArray("groupName");
            arrayLength = extras.getInt("arrayLength");
            countChild = extras.getIntArray("countChild");
            String[] tempArray = new String[arrayLength];
            children = new String[groups.length][arrayLength];
            for (int i=0;i<groups.length;i++) {
                children[i] = extras.getStringArray(groups[i]);

                // TODO delete this block debug ONLY
                Log.i("data", groups[i]+groups.length+" get array loop "+i+" / "+ tempArray.length+"/  countChild: "+countChild[i]);
                for (int j=0;j<children[i].length;j++) {
                    Log.d("data", j+" counter:temparray "+children[i][j]);
                }
            }
        }
        mAdapter = new InspectionMenu(this);
        list.setAdapter(mAdapter);
    }

    public class InspectionMenu extends BaseExpandableListAdapter {

        private Context myContext;

        public InspectionMenu(Context context) {
            myContext = context;
            Log.i("data", "InspectionActivity InspectionMenu children length "+groups.length);
            array_output_data = new int[groups.length][arrayLength];
            array_output_data_quantity = new String[groups.length][arrayLength];
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return null;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return 0;
        }

        @Override
        public View getChildView(final int groupPosition,final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.inspection_row, null);

            TextView childtext = (TextView) convertView.findViewById(R.id.textView1);
            childtext.setText(children[groupPosition][childPosition]);

            final RadioGroup rdg = (RadioGroup) convertView.findViewById(R.id.radioGroup1);
            final RadioButton r1 = (RadioButton) convertView.findViewById(R.id.radio1);
            final RadioButton r2 = (RadioButton) convertView.findViewById(R.id.radio2);
            final RadioButton r3 = (RadioButton) convertView.findViewById(R.id.radio3);
            final EditText inspectQuantity = (EditText) convertView.findViewById(R.id.inspection_quant);

            if (array_output_data[groupPosition][childPosition] >0) {
                //switch (Integer.parseInt(array_output_data[groupPosition][childPosition])) {
                switch (array_output_data[groupPosition][childPosition]) {
                case 1:
                    r1.setChecked(true);
                    break;
                case 2:
                    r2.setChecked(true);
                    break;
                case 3:
                    r3.setChecked(true);
                    break;
                }
            }

            CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
            if (array_output_data[groupPosition][childPosition] > 0) {
                cb.setChecked(true);
                rdg.setVisibility(View.VISIBLE);
                inspectQuantity.setVisibility(View.VISIBLE);
            }

            rdg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    if (checkedId == R.id.radio1) {
                        choice = 1;
                    } else if (checkedId == R.id.radio2) {
                        choice = 2;
                    } else if (checkedId == R.id.radio3) {
                        choice = 3;
                    } else {
                        Log.e("TGTG", "radio button selection invalid in InspectionActivityOld");
                    }
                    array_output_data[groupPosition][childPosition] = (choice);
                }
            });
            cb.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isChecked) {
                    if (isChecked == true) { // display LEVEL (1,2,3) RADIO BUTTONS for this line
                        rdg.setVisibility(View.VISIBLE); // redundant?
                        try {
                            inspectQuantity.setVisibility(View.VISIBLE);    
                        } catch (Exception except) {
                            Log.e("TGTG", "no open inspectQUantity  "+except.getMessage()+"  group "+groupPosition+"  child "+childPosition);
                        }
                        r1.setChecked(true);
                    } else { // hide LEVEL RADIO BUTTONS  for this line
                        rdg.setVisibility(View.GONE);
                        inspectQuantity.setVisibility(View.GONE);
                        rdg.clearCheck();
                        array_output_data[groupPosition][childPosition] = 0;
                        array_output_data_quantity[groupPosition][childPosition] = "";
                    }

                }
            });

            if (array_output_data_quantity[groupPosition][childPosition] != null) {
                inspectQuantity.setText(array_output_data_quantity[groupPosition][childPosition]);
            }

            try  {
                inspectQuantity.addTextChangedListener(new TextWatcher(){

                    @Override
                    public void afterTextChanged(Editable arg0) {
                        array_output_data_quantity[groupPosition][childPosition] = arg0.toString();
                    }

                    @Override
                    public void beforeTextChanged(CharSequence s, int start,
                            int count, int after) {}

                    @Override
                    public void onTextChanged(CharSequence s, int start,
                            int before, int count) {}

                });
            } catch (Exception except) {
                Log.e("TGTG", "did not add listener QUANTITY in inspection");
            }
            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return countChild[groupPosition];
        }

        @Override
        public Object getGroup(int groupPosition) {
            return null;
        }

        @Override
        public int getGroupCount() {
            return groups.length;
        }

        @Override
        public long getGroupId(int groupPosition) {
            return 0;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.group, null);
            TextView grouptext = (TextView) convertView.findViewById(R.id.textView2);
            grouptext.setText(groups[groupPosition]);
            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

    }

}

这些是布局文件: 组.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="64px"
        android:text="TextView" android:textSize="40px" android:paddingLeft="100px" android:paddingTop="10px"/>

</LinearLayout>

inspection_row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" android:id="@+id/ln">
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
            <CheckBox
                android:id="@+id/checkBox1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:layout_gravity="center_vertical"/>
            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center_vertical"
                android:layout_weight="1"
                android:text="weeds" 
                android:textSize="20dip" 
                android:paddingLeft="20px"
                android:gravity="center_vertical"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginTop="-30px"
        >
    <RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="wrap_content"
        android:orientation="horizontal" android:visibility="gone" android:layout_height="wrap_content" android:layout_marginLeft="72px"  android:layout_marginBottom="-10px">
        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="false" android:visibility="visible" android:text="1"/>
        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:checked="false" android:visibility="visible" android:text="2"/>
        <RadioButton
            android:id="@+id/radio3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:checked="false" android:visibility="visible" android:text="3"/>
    </RadioGroup>
    <EditText
        android:id="@+id/inspection_quant"
        android:visibility="gone"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:inputType="number" 
        android:layout_marginLeft="30px"
        android:layout_marginBottom="-10px"/>
    </LinearLayout>
</LinearLayout>

这应该让你的球朝着正确的方向滚动。

【讨论】:

  • 感谢您的宝贵时间。但我的问题是我无法在单击第一个微调器时设置适配器。调试时我的列表为空。现在我设置了第二个微调器的 notify() onclick 但它也无济于事
猜你喜欢
  • 2016-01-22
  • 2012-11-25
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多