Android更改字符串的颜色部分

时间:2016-05-03 15:05:27

标签: android textview

我有一个字符串名称" classe"。它包含许多单词和短语。但是当字符串包含单词"idiom"时,我想要更改颜色。我以编程方式完成了这项工作,但它改变了所有字符串" classe"的颜色。我只是想改变"成语"的颜色。 (单词的一部分,而不是整个短语)。我怎么能以编程方式做到这一点?

    if (classe.contains("idiom")) {

        txtclasse.setTextColor(getResources().getColor(R.color.orange));
    }

2 个答案:

答案 0 :(得分:5)

使用ForegroundColorSpan。

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.whattaspot.R;
import com.whattaspot.parameters.ParameterConst;
import com.whattaspot.utils.ConnectionDetector;
import com.whattaspot.utils.LocationProvider;


public class NewsfeedActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener{

public static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 0x3;
private final int PERMISSION_REQUEST_LOCATION = 0;

private final String TAG = NewsfeedActivity.class.getSimpleName();
private double currentLatitude, currentLongitude;

private String mLastToken;
private LocationProvider mLocationProvider;

private GoogleApiClient mGoogleApiClient;

// views
private View rootView;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;

private LocationRequest mLocationRequest = new LocationRequest();
private Location mLastlocation;




@SuppressWarnings("ConstantConditions")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_newsfeed);

    // Toolbar inizialization
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle(getString(R.string.title_newsfeed).toUpperCase());

    // Restore preferences
    SharedPreferences settings = getSharedPreferences(
            ParameterConst.WHATTASPOT_TOKEN_TYPE, Activity.MODE_APPEND);
    mLastToken = settings.getString(ParameterConst.PARAM_TOKEN_NAME, null);

    // Inizializzo il Location provider
    //mLocationProvider = new LocationProvider(this, this);

    // Initialize views
    rootView = findViewById(R.id.container);
    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.newsfeed_recycler_view);

    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    mRecyclerView.setHasFixedSize(true);

    // use a linear layout manager
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    /* overridePendingTransition(0, 0); */

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);

    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    mLocationRequest = LocationRequest.create()
            .setInterval(10000)
            .setFastestInterval(100)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}

@Override
public void onStop() {
    mGoogleApiClient.disconnect();
    super.onStop();
    Log.d(TAG, "GoogleApiClient disconnect");
    // Disconnect the GoogleApiClient
    //mLocationProvider.disconnect();

}

@Override
public void onStart(){
    mGoogleApiClient.connect();
    super.onStart();
    Log.d(TAG, "GoogleApiClient connect");
}

@Override
public void onResume() {
    super.onResume();
    // Check the internet connection
    if (!ConnectionDetector.isNetworkAvailable(this)) {
        Log.d(TAG, "No Internet connection.");
        Snackbar.make(rootView, "No Internet connection.", Snackbar.LENGTH_LONG).show();


    }

    mGoogleApiClient.connect();
    Log.d(TAG, "GoogleApiClient connect AGAIN");

}

@Override
public void onConnected(Bundle bundle) {
    // Check permission for Android M
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        Log.d(TAG, "Checkpoint 1");


        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {


        } else {
            Log.d(TAG, "Checkpoint 2");

            String permit = String.valueOf(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION));

            Log.d(TAG, permit);

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSION_REQUEST_LOCATION);

            String granted = String.valueOf(PackageManager.PERMISSION_GRANTED);

            Log.d(TAG, permit);
            Log.d(TAG, granted);


        }
    }

    Log.d(TAG, "Checkpoint 3");


}

@Override
public void onLocationChanged(Location location) {
    mLastlocation = location;
}

@Override
public void onConnectionSuspended(int i) {
    Log.d(TAG, "GoogleApiClient connection has been suspended");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.d(TAG, "GoogleApiClient connection failed");
    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution()) {
        try {

            // Start an Activity that tries to resolve the error
            connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
        /*
         * Thrown if Google Play services canceled the original
         * PendingIntent
         */
        } catch (IntentSender.SendIntentException e) {
            // Log the error
            e.printStackTrace();
        }
    } else {
        /*
         * If no resolution is available, display a dialog to the
         * user with the error.
         */
        Log.d(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String[] permissions, int[] grantResults) {

    Log.d(TAG, "In ORPR.");

    switch (requestCode) {
        case PERMISSION_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Log.d(TAG, "Checkpoint ORPR, Yes.");
                if (mLastlocation == null) {
                    try {
                        if(mGoogleApiClient.isConnected()) {
                            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                            mLastlocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                            Log.d(TAG, "Location retrieved.");
                        }
                    } catch (SecurityException ex){
                        Log.d(TAG, "Location not retrieved.");
                    }
                } else {
                    Log.d(TAG, "Location not retrieved");

                }
                Log.d(TAG, "Location changed. New location: " + String.valueOf(mLastlocation.getLatitude()));

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                Log.d(TAG, "Checkpoint ORPR, No.");

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


}

答案 1 :(得分:2)

您可以使用HTML来解决它。

origString = txtclasse.getText().toString();
origString = origString.replaceAll("idiom","<font color='red'>idiom</font>");

txtclasse.setText(Html.fromHtml(origString));