使用微调器更改android:textColor

Tai*_*lor 5 java android spinner android-studio

我设法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" />
Run Code Online (Sandbox Code Playgroud)


这是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();
    }
}
Run Code Online (Sandbox Code Playgroud)


主要活动:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*nko 2

首先,请不要存储View's到静态字段中,它会导致内存泄漏。改变:

static ProgressDialog locate;
static TextView dist, time, speed;
Run Code Online (Sandbox Code Playgroud)

private ProgressDialog locate;
private TextView dist, time, speed;
Run Code Online (Sandbox Code Playgroud)

然后,根据您的目的,您可以使用SharedPreferences。让我们一步一步来吧。

  1. 将以下字段添加到Einstellungen

    public static final String SHARED_PREFERENCES = "SHARED_PREFS";
    public static final String SELECTED_COLOR = "SELECTED_COLOR";
    private SharedPreferences preferences;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 获取SharedPreferences内部onCreate()方法:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_einstellungen);
        preferences = getSharedPreferences(SHARED_PREFERENCES, MODE_PRIVATE);
        ...
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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;
    
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

在你的MainActivity

  1. 添加下一个字段:

    private SharedPreferences preferences;
    
    Run Code Online (Sandbox Code Playgroud)
  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();
    }
    
    Run Code Online (Sandbox Code Playgroud)

更新:
如果你想保存微调器状态,你还可以使用SharedPreferences

  1. 在 Einstellungen 中添加另一个常数:

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

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

    int position = preferences.getInt(SELECTED_COLOR_POSITION, 0);
    spinner.setSelection(position);
    
    Run Code Online (Sandbox Code Playgroud)