常见控件3-下拉列表框(Spinner)
下拉列表框(Spinner) |
1、布局 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
|
2、代码: package cn.zengfansheng.spinner;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends Activity { protected static final String TAG = "MainActivity";
private Spinner spinner; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); spinner = (Spinner) this.findViewById(R.id.spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("JAVA");
adapter.add("PHP");
adapter.add("C++");
adapter.add("Object-C");
adapter.add("C");
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// Spinner spinner = (Spinner) view;
// String itemContent = (String)parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
Log.i(TAG, parent.getClass().getName());
}
});
}
} |
结果: |