简体   繁体   中英

Change drawable color for home-screen widget

I have a home-screen widget the background color of this widget needs to change. I tried this code: remoteViews.setInt(R.id.background, "setBackgroundColor", MY_COLOR);

But the code change all background. And I want background with rounded corners.

Also I tried this remoteViews.setInt(R.id.background, "setBackgroundResource", R.drawable.background2); But this is a static method and I need to dynamically change the color

I also tried to add CardView to the xml widget. But this cannot be done

How can I change drawable color?

FIRST UPDATE

在此处输入图像描述

SECOND UPDATE

This is my WidgetProvider.java:

public class WidgetProvider extends AppWidgetProvider {

String description, temp;
boolean weatherTrue = false;
RemoteViews views;
String icon_code;
FirebaseFirestore db = FirebaseFirestore.getInstance();
ArrayList<Time> times = new ArrayList<>();
ArrayList<Time> near_times = new ArrayList<>();
String currentTime;
String city = "", lang_code = "ru";
boolean isWeatherLoaded = false, isTimeDescriptionLoaded = false;

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    currentTime = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());

    for(int appWidgetId : appWidgetIds){
        EventChangeListener();
        Intent intent = new Intent(context, StartActivity.class);
        intent.putExtra("is_from_widget",true);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 , intent, PendingIntent.FLAG_CANCEL_CURRENT);

        WeatherDB weatherDB = new WeatherDB(context);
        SQLiteDatabase weather_database = weatherDB.getWritableDatabase();
        Cursor weather_cursor = weather_database.query(WeatherDB.TABLE_WEATHER,null,null,null,null,null,null);
        if(weather_cursor.moveToFirst()){
            int weatherId = weather_cursor.getColumnIndex(WeatherDB.KEY_WEATHER);
            do {
                weatherTrue = Boolean.parseBoolean(weather_cursor.getString(weatherId));
            } while (weather_cursor.moveToNext());
        }
        weather_cursor.close();

        LangDB dbHelper = new LangDB(context);
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        Cursor cursor = database.query(LangDB.TABLE_LANG,null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            int langCodeIdIndex = cursor.getColumnIndex(LangDB.KEY_LANG_CODE);
            do {
                lang_code = cursor.getString(langCodeIdIndex);
            } while (cursor.moveToNext());
        }
        cursor.close();

        CityDB cityDB = new CityDB(context);
        SQLiteDatabase city_database = cityDB.getWritableDatabase();
        Cursor city_cursor = city_database.query(CityDB.TABLE_CITY,null,null,null,null,null,null);
        if(city_cursor.moveToFirst()){
            int cityCOdeId = city_cursor.getColumnIndex(CityDB.KEY_CITY);
            do {
                city = city_cursor.getString(cityCOdeId);
            } while (city_cursor.moveToNext());
        }
        city_cursor.close();

        // HERE IS THE CODE !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        Drawable unwrappedDrawable =
                    AppCompatResources.getDrawable(context, R.drawable.widget_background);
        Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
        DrawableCompat.setTint(wrappedDrawable, Color.RED);

        if(weatherTrue) {
            if(city.equals("")) city="питер";
            String url = "https://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=2dcda451bffbded334cc59bb0cece826&lang="+lang_code+"&units=metric";
            new GetURLData().execute(url);
            views = new RemoteViews(context.getPackageName(), R.layout.widget_weather);
            SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMMM",new Locale(lang_code));
            Date d = new Date();
            String dateString = sdf.format(d);
            dateString = dateString.substring(0, 1).toUpperCase() + dateString.substring(1).toLowerCase();
            views.setTextViewText(R.id.date, dateString);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean isWhile = true;

                    while(isWhile){
                        if(isTimeDescriptionLoaded&&isWeatherLoaded) {
                            isWhile = false;

                            description = description.substring(0, 1).toUpperCase() + description.substring(1).toLowerCase();
                            views.setTextViewText(R.id.weather_description, description);
                            views.setTextViewText(R.id.temp, temp);
                            views.setOnClickPendingIntent(R.id.more_btn, pendingIntent);

                            ArrayList<String> descriptions_ru = new ArrayList<>();
                            ArrayList<String> descriptions_en = new ArrayList<>();

                            if (near_times.size() > 0) {
                                if (near_times.get(0).description1Ru != null && near_times.get(0).description1Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description1Ru);
                                    descriptions_en.add(near_times.get(0).description1En);
                                }
                                if (near_times.get(0).description2Ru != null && near_times.get(0).description2Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description2Ru);
                                    descriptions_en.add(near_times.get(0).description2En);
                                }
                                if (near_times.get(0).description3Ru != null && near_times.get(0).description3Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description3Ru);
                                    descriptions_en.add(near_times.get(0).description3En);
                                }
                                if (near_times.get(0).description4Ru != null && near_times.get(0).description4Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description4Ru);
                                    descriptions_en.add(near_times.get(0).description4En);
                                }
                                if (near_times.get(0).description5Ru != null && near_times.get(0).description5Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description5Ru);
                                    descriptions_en.add(near_times.get(0).description5En);
                                }

                                if (lang_code.equals("ru"))
                                    views.setTextViewText(R.id.description, descriptions_ru.get(randInt(0, descriptions_ru.size())));
                                if (lang_code.equals("en"))
                                    views.setTextViewText(R.id.description, descriptions_en.get(randInt(0, descriptions_ru.size())));
                            }

                            Uri uri = null;
                            if (icon_code.equals("01d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d01);
                            if (icon_code.equals("02d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d02);
                            if (icon_code.equals("03d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d03);
                            if (icon_code.equals("04d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d04);
                            if (icon_code.equals("09d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d09);
                            if (icon_code.equals("10d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d10);
                            if (icon_code.equals("11d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d11);
                            if (icon_code.equals("13d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d13);
                            if (icon_code.equals("50d"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.d50);

                            if (icon_code.equals("01n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n01);
                            if (icon_code.equals("02n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n02);
                            if (icon_code.equals("03n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n03);
                            if (icon_code.equals("04n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n04);
                            if (icon_code.equals("09n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n09);
                            if (icon_code.equals("10n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n10);
                            if (icon_code.equals("11n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n11);
                            if (icon_code.equals("13n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n13);
                            if (icon_code.equals("50n"))
                                uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.drawable.n50);

                            views.setImageViewUri(R.id.weather_icon, uri);
                            appWidgetManager.updateAppWidget(appWidgetId, views);

                        }
                    }
                }
            }).start();
        } else {
            views = new RemoteViews(context.getPackageName(), R.layout.widget);
            SimpleDateFormat sdf = new SimpleDateFormat("EEEE, dd MMMM",new Locale(lang_code));
            Date d = new Date();
            String dateString = sdf.format(d);
            dateString = dateString.substring(0, 1).toUpperCase() + dateString.substring(1).toLowerCase();
            views.setTextViewText(R.id.date, dateString);

            new Thread(new Runnable() {
                @Override
                public void run() {

                    boolean isWhile = true;

                    while(isWhile) {

                        if (isTimeDescriptionLoaded) {

                            isWhile = false;

                            ArrayList<String> descriptions_ru = new ArrayList<>();
                            ArrayList<String> descriptions_en = new ArrayList<>();

                            if (near_times.size() > 0) {
                                if (near_times.get(0).description1Ru != null && near_times.get(0).description1Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description1Ru);
                                    descriptions_en.add(near_times.get(0).description1En);
                                }
                                if (near_times.get(0).description2Ru != null && near_times.get(0).description2Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description2Ru);
                                    descriptions_en.add(near_times.get(0).description2En);
                                }
                                if (near_times.get(0).description3Ru != null && near_times.get(0).description3Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description3Ru);
                                    descriptions_en.add(near_times.get(0).description3En);
                                }
                                if (near_times.get(0).description4Ru != null && near_times.get(0).description4Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description4Ru);
                                    descriptions_en.add(near_times.get(0).description4En);
                                }
                                if (near_times.get(0).description5Ru != null && near_times.get(0).description5Ru != null) {
                                    descriptions_ru.add(near_times.get(0).description5Ru);
                                    descriptions_en.add(near_times.get(0).description5En);
                                }

                                if (lang_code.equals("ru"))
                                    views.setTextViewText(R.id.description, descriptions_ru.get(randInt(0, descriptions_ru.size())));
                                if (lang_code.equals("en"))
                                    views.setTextViewText(R.id.description, descriptions_en.get(randInt(0, descriptions_ru.size())));
                            }

                            views.setOnClickPendingIntent(R.id.more_btn, pendingIntent);
                            appWidgetManager.updateAppWidget(appWidgetId, views);

                        }
                    }

                }
            }).start();

        }
    }
}

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
}

@SuppressLint("NotifyDataSetChanged")
private void near_time(){
    near_times.clear();
    for (Time cheese : times) {
        if(Integer.parseInt(cheese.time.replace(":","")) >= Integer.parseInt(currentTime.replace(":",""))) {
            Time time_add = new Time(cheese.time,
                    cheese.description1Ru,
                    cheese.description1En,
                    cheese.description2Ru,
                    cheese.description2En,
                    cheese.description3Ru,
                    cheese.description3En,
                    cheese.description4Ru,
                    cheese.description4En,
                    cheese.description5Ru,
                    cheese.description5En,
                    cheese.longDescriptionRu,
                    cheese.longDescriptionEn);
            near_times.add(time_add);
        }
    }
    int time_size = near_times.size();
    for(int x=0; x < 4-time_size; x++){
        if(near_times.size() < 4) {
            near_times.add(times.get(x));
        }
    }
    isTimeDescriptionLoaded = true;
}

public int randInt(int min, int max) {
    return (int) ((Math.random() * (max - min)) + min);
}

private void EventChangeListener(){
    times.clear();
    db.collection("main").orderBy("time", Query.Direction.ASCENDING)
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @SuppressLint("NotifyDataSetChanged")
                @Override
                public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                    if (error != null){
                        return;
                    }
                    for (DocumentChange dc : value.getDocumentChanges()){
                        if(dc.getType() == DocumentChange.Type.ADDED){
                            times.add(dc.getDocument().toObject(Time.class));
                        }
                    }
                    near_time();
                }
            });
}

private class GetURLData extends AsyncTask<String, String, String> {
    protected  void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected String doInBackground(String... strings) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(strings[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuilder builder = new StringBuilder();
            String line = "";
            while((line = reader.readLine()) !=null)
                builder.append(line).append("\n");
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null)
                connection.disconnect();
            try {
                if (reader != null)
                    reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return  null;
    }
    @SuppressLint("SetTextI18n")
    @Override
    protected  void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            try {
                JSONObject jsonObject = new JSONObject(result);
                description = jsonObject.getJSONArray("weather")
                        .getJSONObject(0)
                        .getString("description");
                temp = jsonObject.getJSONObject("main").getInt("temp") + "°C";
                icon_code = jsonObject.getJSONArray("weather")
                        .getJSONObject(0)
                        .getString("icon");
                isWeatherLoaded = true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

}

drawable>New>Drawable Resource File name:my_drawable

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/MY_COLOR"/>
    <corners android:radius="20dp"/>

</shape>

YouActivity

Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, R.drawable.my_drawable); 
Drawable wrappedDrawable = DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(wrappedDrawable, Color.RED);

youColorInt will be the color you want to give

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM