为膨胀视图中的元素分配任何唯一标识符

Assign any unique identifier to elements in a inflated view

我想知道我们是否可以为膨胀视图内的元素分配任何唯一编号。

我的视图看起来像这样,这张图片可能会让您了解我正在尝试做什么:

我想做的是根据这样选择的微调项更改编辑文本框的值:

//spinnerPlanItinerary is the first spinner
    spinnerPlanItinerary.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<Town> listOfTowns = new ArrayList<Town>();
                ArrayAdapter<Town> townplanitineraryadapter2 = new ArrayAdapter<Town>(this,
                        android.R.layout.simple_dropdown_item_1line, listOfTowns);
                townplanitineraryadapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinnerTown.setAdapter(townplanitineraryadapter2);
                spinnerTown.setText(""); //second spinner in the view
                edBelt.setText(""); //first edit text in the view
                edStrata.setText(""); //second edit text in the view

                townplanitineraryadapter2.notifyDataSetChanged();
            }
        });

我无法为该元素指定任何唯一 ID,因为它们在我的布局文件中已有 ID。我也一直在使用 setTag()getTag()getTag() 没有给我任何东西。

另请注意,卡片视图会在单击如下按钮时膨胀:

final LinearLayout itineraryDetailLL = (LinearLayout) findViewById(R.id.itineraryDetailLinearlayout);

        final View childView = getLayoutInflater().inflate(R.layout.cardview, null);
        itineraryDetailLL.addView(childView);

如果您想更改 EditText 的值,则不需要为此设置唯一标识符。你可以这样做:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

       public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub

        if (spinner.getSelectedItem().toString().equals("someSpinnerData")) {
                  editText.setText("yourDesiredText");    
        } else if (spinner.getSelectedItem().toString().equals("someSpinnerData2")) {
                  editText.setText("someSpinnerData2");    
        }
    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
});

感谢您在评论中澄清。

根据我现在的了解,您可以动态扩充并添加额外的文本字段。那么他们都有相同的ID,正确。

那么,怎么区分呢? 简单的解决方案:

final View childView = getLayoutInflater().inflate(R.layout.cardview, null);
itineraryDetailLL.addView(childView);

您不应只创建一个 childView 成员,而应创建一个成员列表(或字典,或任何最适合您下一步操作的内容)。 在其中的 中,您可以为该视图中包含的编辑文本的 ID 执行 .findViewById

所以,也许它看起来像这样:

Map<Integer, View> myChilds = new ....
final View childView = getLayoutInflater().inflate(R.layout.cardview, null);
itineraryDetailLL.addView(childView);
// Here is your "make it unique" part:
myChilds.put(your_next_unique_id, childView);
...
// When you want to access them
EditText txt = myChilds.get(my_unique_id).findViewById(xml_id_of_edittext);
txt.setText("...");

我希望您知道这可以将您引向何方。 干杯,格里斯