您的位置:首页 > 其它

如何拿到Spinner的当前值,并实时传递至TextView中显示

2014-05-13 16:56 381 查看
下午项目中,要用到这个东西:

拿到Spinner的当前值,并把拿到的值,实时传递给TextView,然后,显示在TextView当中。

布局文件是这样的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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="40dp"
        android:entries="@array/tools"
        />
    
    <View 
        android:layout_width="match_parent"
        android:layout_height="50dp"
        />
    <TextView 
        android:id="@+id/txt01"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="hello world"
        />
</LinearLayout>


后来,经过黄老尸指点,终于找到了解决方案:

1、给Spinner添加一个监听器;

2、点击Spinner,选择值后,直接把 选中的值,设置为TextView的值。

整体代码如下:

package com.zhanggeng.spinnertest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {

	private Spinner  sp;
	private TextView tv;
	private String str;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		sp = (Spinner) findViewById(R.id.spinner);
		tv = (TextView) findViewById(R.id.txt01);
		str = (String) sp.getSelectedItem();
		sp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				
				//拿到被选择项的值
				str = (String) sp.getSelectedItem();
				//把该值传给 TextView
				tv.setText(str);
			}

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

}


在解决这个问题时,我碰到的问题:

1、我不知道,给Spinner添加的监听器,是哪个?习惯了用,View , DialogInterface 中的监听器,突然间要添加一个 OnItemSelectedListener 不知道在哪个包里!

事实上在这里:import android.widget.AdapterView.OnItemSelectedListener;

2、不知道,怎么去,拿当前值,后来在网上,查找后,发现有个 getSeletedItem() 方法,加上后,就OK了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: