使用Spinner更改android:textColor

5
我成功地在我的代码中使用了一个“spinner”,并希望通过该“spinner”更改“MainActivity”文件中某个文本的“textColor”,但它位于另一个类文件“Einstellungen”中。 是否可能从另一个活动更改当前活动中的文本颜色? 这是我想要更改文本颜色的“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(红色)。 - Tailor
在您的项目选择监听器中,只需添加description.setTextColor即可。 - Vidhi Dave
像这样吗? case 0:description.setText("" + des [i]); textview.setTextColor(color); break; case 1:... - Tailor
我添加了:MainActivity.speed.setTextColor(Color.WHITE); 但是如果我按按钮切换回Einstellungen活动,它只会显示1秒钟的颜色。 - Tailor
我认为问题在于Spinner案例仅在Einstellungen活动中加载..这可能吗?例如,如果我点击案例0,MainActivity.speed.setTextColor(Color.WHITE);必须在MainActivity中处于活动状态,但我认为它并没有:/ - Tailor
显示剩余4条评论
1个回答

2

首先,请勿将View存储在静态字段中,这会导致内存泄漏。请更改为:

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

为了

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

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

  1. Add the next fields to Einstellungen:

    public static final String SHARED_PREFERENCES = "SHARED_PREFS";
    public static final String SELECTED_COLOR = "SELECTED_COLOR";
    private SharedPreferences preferences;
    
  2. Get SharedPreferences inside onCreate() method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_einstellungen);
        preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE);
        ...
    }
    
  3. Put selected color to 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. Add the next field:

    private SharedPreferences preferences;
    
  2. Inside onCreate() method, get selected color and set it to 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();
    }
    

更新:
如果您希望保存Spinner状态,还可以使用SharedPreferences

  1. Add another one constant to Einstellungen:

    public static final String SELECTED_COLOR_POSITION = "SELECTED_COLOR_POSITION";
    
  2. Add the next line at the beginning of your onItemSelected() method, to save selected item position:

    preferences.edit().putInt(SELECTED_COLOR_POSITION, i).apply();
    
  3. Restore state of the spinner in the onCreate() method, after spinner.setAdapter(adapter) line:

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

我已经添加了你的代码行,没有出现任何错误。但是应用程序仍然不断崩溃 :/ - Tailor
1
@Tailor,抱歉是我代码中的错误。我已经更新了我的答案。请在MainActivity中更改你的onCreate()方法。 - Denysole
哇,谢谢你,它正在工作 :) 你知道是否可以保存微调器的状态吗?在我的情况下,如果我在微调器上选择蓝色并使用按钮切换到主活动,则颜色为蓝色。但是,如果我切换回微调器活动,则选择的是白色而不是蓝色了。 - Tailor
@Tailor,是的,这是可能的,我已经添加了代码来实现。 - Denysole
嘿,我有另一个问题。是否可以以相同的方式更改TextSize?我再次尝试了switch cases,但它没有起作用:/ switch(d){ case 0: description2.setText(des2 [d]); preferences2.edit()。putInt(SELECTED_SIZE,????); <==您知道我在putInt内部必须调用什么吗? - Tailor
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接