我创建了一个带有SpinnerTextView的Android应用程序.我希望在TextView中显示微调器下拉列表中的选定项.我在onCreate方法中实现了微调器,因此当我运行程序时,它会在TextView中显示一个值(在从下拉列表中 Select 一项之前).

我只想在从下拉列表中 Select 一个项目后在文本视图中显示该值.我该怎么做?

以下是我的代码:

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

public class GPACal01Activity extends Activity implements OnItemSelectedListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Spinner spinner = (Spinner) findViewById(R.id.noOfSubjects);

        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.noofsubjects_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(this);
    }

    public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
        TextView textView = (TextView) findViewById(R.id.textView1);
        String str = (String) parent.getItemAtPosition(pos);
        textView.setText(str);
    }

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

    }
}

推荐答案

spinner.setOnItemSelectedListener(this); // Will call onItemSelected() Listener.

所以第一次用任何整数值处理这个问题

例子:

public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
   if(++check > 1) {
      TextView textView = (TextView) findViewById(R.id.textView1);
      String str = (String) parent.getItemAtPosition(pos);
      textView.setText(str);
   }
}

可以使用布尔值,也可以通过判断当前和以前的位置来实现.See here

Android相关问答推荐

如何处理谷歌未经证实的应用程序拒绝?

如何更新Kotlin中的显示?

在Jetpack Compose中,如何判断屏幕是否已重新组合?

Android在NavHost中的LazyColumn中编写约束布局:error - replace()在未放置的项目上调用

如何从URI中获取图像大小

学习Kotlin问题.无法理解Modifier参数

Jetpack Compose X.dp 性能问题?

Android Compose - 为什么 Canvas 中的drawText在底部被切断而不是在顶部?

如何在卡片视图右侧添加箭头

如何在jetpack compose中使可组合的屏幕zoom 到不同的手机(屏幕)尺寸?

从 Jetpack Compose 中的 IconButton 中删除黑色色调

修复错误 Invariant Violation: requireNativeComponent: "RNSScreenStackHeaderConfig" was not found in the UIManager

Android Studio:按下前缀键:切换 Logcat 格式

如何在 Jetpack Compose 中的 VisualTransformation 之后将光标保持在文本字段的末尾

我的 React Native 在 11 月 4 日之前运行良好,但现在在运行 yarn android 时抛出异常

重命名列失败的房间自动迁移(NOT NULL 约束失败,生成错误的迁移类)

是什么让 Android Studio 中的按钮变成紫色?加上新手的其他奇怪行为

如何使用 Jetpack Compose 在应用程序中实现本地化

Delphi 11:以编程方式查找 MSBuild 的正确工具版本

如何在 Android Studio 中使用 Github Copilot?