Spinner의 OnItemClickListener에 연결합니다. 그런 다음 선택한 항목이 "새 카테고리 추가"인지 확인하십시오.
예인 경우 대화 상자를 표시하여 새 항목을 추가하십시오.
새 항목을 추가하는 동안
,
- 는 "새로운 카테고리를 추가"마지막 항목을 제거합니다.
- 입력 한 새 범주를 추가하십시오.
- 그런 다음 "새 카테고리 추가"항목을 다시 추가하십시오.
이렇게하면 "새 카테고리 추가"항목이 마지막으로 추가됩니다.
코드 샘플 :
레이아웃 main.xml에 :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10" >
<Spinner
android:id="@+id/cmbNames"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
레이아웃 spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
활동 클래스 :이 알고
public class MainActivity extends Activity {
private static final String NAME = "name";
private static final String ADD_NEW_ITEM = "Add New Item";
private SimpleAdapter adapter;
private Spinner cmbNames;
private List<HashMap<String, String>> lstNames;
private int counter;
private OnItemSelectedListener itemSelectedListener = new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
HashMap<String, String> map = lstNames.get(arg2);
String name = map.get(NAME);
if (name.equalsIgnoreCase(ADD_NEW_ITEM)) {
lstNames.remove(map);
counter++;
addNewName(String.valueOf(counter));
addNewName(ADD_NEW_ITEM);
adapter.notifyDataSetChanged();
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateList();
cmbNames = (Spinner) findViewById(R.id.cmbNames);
adapter = new SimpleAdapter(this, lstNames, R.layout.spinner_item,
new String[] { NAME }, new int[] { R.id.tvName });
cmbNames.setAdapter(adapter);
cmbNames.setOnItemSelectedListener(itemSelectedListener);
}
private void populateList() {
lstNames = new ArrayList<HashMap<String, String>>();
addNewName("abc");
addNewName("pqr");
addNewName("xyz");
addNewName(ADD_NEW_ITEM);
}
private void addNewName(String name) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(NAME, name);
lstNames.add(map);
}
}
. 그러나'OnItemSelectedListener'에서 어떻게 처리 할 수 있습니까? –
u 항목을 선택하면 u 항목을 선택할 수 있습니다. 선택한 항목을 미리 정의 된 항목과 일정하게 비교하십시오. 선택한 항목이 미리 정의 된 항목 인 경우 작업을 수행하십시오 – Braj
작동하지 않습니다. 이 'parent.getItemAtPosition (position) .toString();'이 위치를 반환하고이를 문자열로 변환하기 때문에 나는 생각한다. –