Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Spiner 添加與刪除數據

Android Spiner 添加與刪除數據

編輯:關於Android編程

package com.example.arraylist;


import java.util.ArrayList;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;


public class MainActivity extends
Activity {


private static final String[] places = {"銅鼓","大段","古橋"};
TextView mTextView;
EditText mEditText;
Button mButton1, mButton2;
Spinner spinner;
ArrayAdapter<String> adapter1;
ArrayList<String> list1;


@Override
public void onCreate(
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list1=new ArrayList<String>();
for (int i = 0; i < places.length; i++) {

list1.add(places[i]);
}

adapter1=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list1);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mTextView=(TextView)findViewById(R.id.textView1);
mEditText=(EditText)findViewById(R.id.editText1);
mButton1=(Button)findViewById(R.id.button1);
mButton2=(Button)findViewById(R.id.button2);
spinner=(Spinner)findViewById(R.id.spinner1);


spinner.setAdapter(adapter1);


mButton1.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

String newplace=mEditText.getText().toString();


for (int i = 0; i < adapter1.getCount(); i++) {

if (newplace.equals(adapter1.getItem(i))) {

return;
}


}

if (!newplace.equals("")) {

adapter1.add(newplace);
int position=adapter1.getPosition(newplace);

spinner.setSelection(position);
mEditText.setText("");
}

}
});

mButton2.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub

 

if (spinner.getSelectedItem()!=null) {

adapter1.remove(spinner.getSelectedItem().toString());

mEditText.setText("");
if (adapter1.getCount()==0) {
mTextView.setText("");
}

}
}
});

spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {


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

 

mTextView.setText(arg0.getSelectedItem().toString());
}


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

}
});
}


@Override
public boolean onCreateOptionsMenu(
Menu menu) {
getMenuInflater().inflate(
R.menu.activity_main,
menu);
return true;
}
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved