我在下面创建了这个类:
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
EditText edit = (EditText) view.findViewById(R.id.editText2);
edit.setText(parent.getItemAtPosition(pos).toString());
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
当我尝试在其他布局中更改edittext的值时,会出现错误。我将以下代码放在我的主要活动中
rootView = inflater.inflate(R.layout.food, container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
在我更改主活动的布局后,我为该布局中的微调器设置了setOnItemSelectedListener。
这是我的food.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:background="#d0dae9"
android:orientation="vertical">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:spinnerMode="dropdown"
android:entries="@array/foodcategory"
android:layout_weight="1" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner1"
android:entries="@array/foodcategory1"
android:layout_weight="1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"
android:id="@+id/button2"
android:layout_weight="1" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_gravity="center_horizontal"
android:layout_weight="1" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="@+id/editText2"
android:layout_gravity="center_horizontal"
android:layout_weight="1" />
</LinearLayout>
以下是微调项目
<string-array name="foodcategory">
<item>Drinks</item>
<item>Meal</item>
<item>Meat</item>
<item>Snacks</item>
<item>Breads</item>
<item>Cakes</item>
<item>Fruits</item>
<item>Vegies</item>
<item>Other</item>
</string-array>
请帮帮我..
答案 0 :(得分:0)
更新CustomOnItemSelectedListener类:
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
private final View rootView;
public CustomOnItemSelectedListener(View root) {
rootView = root;
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
EditText edit = (EditText) rootView.findViewById(R.id.editText2);
edit.setText(parent.getItemAtPosition(pos).toString());
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
将rootView作为参数添加到CustomOnItemSelectedListener构造函数:
rootView = inflater.inflate(R.layout.food, container, false);
Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener(rootView));