【问题标题】:Change android:textColor with a spinner使用微调器更改 android:textColor
【发布时间】:2018-02-07 00:22:21
【问题描述】:

我设法在我的代码中使用了spinner,并想通过该微调器更改MainActivity 文件中某个文本的textColor,但他位于另一个类文件中-Einstellungen。 是否可以从另一个活动中更改当前活动中的 textColor?

这是我要更改文本颜色的main_activity.xml

<TextView
    android:id="@+id/speedtext"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="180dp"
    android:gravity="center"
    android:singleLine="true"
    android:text="TEXT"
    android:textColor="@android:color/white"
    android:textSize="220sp" />


这是 Einstellungen 活动:

public class Einstellungen extends AppCompatActivity {
    String[] names = {"Weiß", "Blau", "Rot"};
    String[] des = {"Weiß", "Blau", "Rot"};
    ArrayAdapter<String> adapter;
    Spinner spinner;
    TextView description;

    public Button button;

    public void init() {
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent toy = new Intent(Einstellungen.this, MainActivity.class);
                startActivity(toy);
            }
        });
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_einstellungen);
        spinner = (Spinner) findViewById(R.id.spinner);
        description = (TextView) findViewById(R.id.text);
        adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, names);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i) {
                    case 0:
                        description.setText("" + des[i]);
                        MainActivity.speed.setTextColor(Color.WHITE);
                        break;
                    case 1:
                        description.setText("" + des[i]);
                        MainActivity.speed.setTextColor(Color.BLUE);
                        break;
                    case 2:
                        description.setText("" + des[i]);
                        MainActivity.speed.setTextColor(Color.RED);
                        break;

                }
            }

            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        init();
    }
}


MainActivity:

public class MainActivity extends AppCompatActivity  {

    LocationService myService;
    static boolean status;
    LocationManager locationManager;
    static TextView dist, time, speed;
    static long startTime, endTime;
    ImageView image;
    static ProgressDialog locate;
    static int p = 0;

    private ServiceConnection sc = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            LocationService.LocalBinder binder = (LocationService.LocalBinder) service;
            myService = binder.getService();
            status = true;
        }

        public void onServiceDisconnected(ComponentName name) {
            status = false;
        }
    };

    public Button button;
    public void init() {
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent toy = new Intent(MainActivity.this, Einstellungen.class);
                startActivity(toy);
            }
        });
    }

    void bindService() {
        if (status == true)
            return;
        Intent i = new Intent(getApplicationContext(), LocationService.class);
        bindService(i, sc, BIND_AUTO_CREATE);
        status = true;
        startTime = System.currentTimeMillis();
    }

    void unbindService() {
        if (status == false)
            return;
        Intent i = new Intent(getApplicationContext(), LocationService.class);
        unbindService(sc);
        status = false;
    }

    protected void onResume() {
        super.onResume();

    }

    protected void onStart() {
        super.onStart();

    }

    protected void onDestroy() {
        super.onDestroy();
        if (status == true)
            unbindService();
    }

    public void onBackPressed() {
        if (status == false)
            super.onBackPressed();
        else
            moveTaskToBack(true);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        speed = (TextView) findViewById(R.id.speedtext);
        image = (ImageView) findViewById(R.id.image);
        start();
        init();
    }

    public void start() {
        checkGps();
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

            return;
        }


        if (status == false)
            bindService();
        locate = new ProgressDialog(MainActivity.this);
        locate.setIndeterminate(true);
        locate.setCancelable(false);
        locate.setMessage("Suche GPS-Signal");
        locate.show();
    }


    void checkGps() {
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {


            showGPSDisabledAlertToUser();
        }
    }

    private void showGPSDisabledAlertToUser() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Bitte GPS aktivieren")
                .setCancelable(false)
                .setPositiveButton("GPS aktivieren",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent callGPSSettingIntent = new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(callGPSSettingIntent);
                            }
                        });
        alertDialogBuilder.setNegativeButton("Abbrechen",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }
}

【问题讨论】:

  • 您将从微调器中选择一个项目,然后导航到另一个页面,您希望看到文本颜色的变化?这就是你想要的吗?
  • 如果我打开应用程序,文本颜色为白色。但我希望能够通过该微调器将这种颜色更改为另一种颜色。我不想导航到另一个页面 :) 我想编辑主页。你明白 ?有点难解释^^
  • 确实是 :).. 一个问题,文本颜色会根据微调器中选择的项目而改变?
  • 是的,完全正确。在这种情况下,Spinner 内的物品是 Weiß(白色)、Blau(蓝色)和 Rot(红色)。
  • 在您的项目选择列表中,只需添加 description.setTextColor

标签: java android android-studio spinner


【解决方案1】:

首先,请不要将View's 存储到静态字段中,它会导致Memory leaks。变化:

static ProgressDialog locate;
static TextView dist, time, speed;

private ProgressDialog locate;
private TextView dist, time, speed;

然后,为了您的目的,您可以使用SharedPreferences。让我们一步一步来。

  1. 将下一个字段添加到Einstellungen

    public static final String SHARED_PREFERENCES = "SHARED_PREFS";
    public static final String SELECTED_COLOR = "SELECTED_COLOR";
    private SharedPreferences preferences;
    
  2. onCreate()方法中获取SharedPreferences

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_einstellungen);
        preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE);
        ...
    }
    
  3. 把选中的颜色放到SharedPreferences:

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        switch (i) {
            case 0:
                description.setText(des[i]);
                preferences.edit().putInt(SELECTED_COLOR, Color.WHITE).apply();
                break;
            case 1:
                description.setText(des[i]);
                preferences.edit().putInt(SELECTED_COLOR, Color.BLUE).apply();
                break;
            case 2:
                description.setText(des[i]);
                preferences.edit().putInt(SELECTED_COLOR, Color.RED).apply();
                break;
    
        }
    }
    

在你的MainActivity:

  1. 添加下一个字段:

    private SharedPreferences preferences;
    
  2. onCreate()方法中,获取选中的颜色并将其设置为TextView

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        speed = findViewById(R.id.speedtext);
        image = findViewById(R.id.image);
    
        preferences = getSharedPreferences(Einstellungen.SHARED_PREFERENCES, MODE_PRIVATE);
        int color = preferences.getInt(Einstellungen.SELECTED_COLOR, Color.WHITE);
        speed.setTextColor(color);
        init();
    }
    

更新:
如果要保存微调器状态,也可以使用SharedPreferences

  1. 向 Einstellungen 添加另一个常量:

    public static final String SELECTED_COLOR_POSITION = "SELECTED_COLOR_POSITION";
    
  2. onItemSelected() 方法的开头添加下一行,以保存所选项目的位置:

    preferences.edit().putInt(SELECTED_COLOR_POSITION, i).apply();
    
  3. onCreate() 方法中恢复微调器的状态,在spinner.setAdapter(adapter) 行之后:

    int position = preferences.getInt(SELECTED_COLOR_POSITION, 0);
    spinner.setSelection(position);
    

【讨论】:

  • 我已经添加了你的行并且没有错误。该应用程序不断崩溃:/
  • @Tailor,抱歉,这是我的代码中的错误。我已经更新了我的答案。请在MainActivity 中更改您的onCreate() 方法
  • 哇,谢谢伙计,它正在工作:) 你知道是否可以保存微调器的状态吗?就我而言,如果我在微调器上选择蓝色并使用按钮切换到 mainactivity,则颜色为蓝色。但是,如果我切换回微调器活动,则会选择白色而不是蓝色。
  • @Tailor,是的,这是可能的,我已经添加了代码来做到这一点。
  • 格式精美且详细的答案,比我见过的一些更高代表的帖子要好。流畅,不夸张。尽管您至少应该添加一些关于 为什么 将字段设为私有(封装)的来源:考虑到它们缺乏适当的访问修饰符,它们不需要私有,可能会使 OP 感到困惑. +1 任一方式
猜你喜欢
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多