当前位置: 首页 > 知识库问答 >
问题:

尝试显示我的应用程序的天气图标时遇到问题

谷梁煌
2023-03-14

这是大约20天前被问及的,当时我正试图在我的应用程序上显示天气图标,这是根据天气官方API文档中列出的天气状况数量,城市的反应(从可绘制的文件夹中)https://openweatherhtml" target="_blank">map.org/weather-conditions(您始终可以通过检查编辑历史来查看)。API提供了9种主要天气条件。

这仍然是我的目标:

>

  • 当应用程序首次打开时,不显示任何图标。

    如果用户搜索一个城市,得到的回应是晴朗的天空,则显示晴朗的天气图标;

    否则,如果响应是该城市中的少数云,则显示少数云图标

    否则,如果响应是该城市中的分散云,则显示分散云图标

    否则,如果该城市的响应是“破碎的云”,则显示“破碎的云朵”图标

    否则,如果响应是该城市的阵雨,则显示阵雨图标

    否则,如果响应是该城市有雨,则显示雨图标

    否则,如果响应是该城市的Thunder的雷暴,显示雷暴图标

    否则,如果响应是该城市下雪,则显示下雪图标

    否则,如果该城市的响应为“雾”,则显示“雾”图标。

    在马格达莱娜·罗维卡的帮助下,我已经能够实现一些事情,但即使尝试自己修复它,这个问题仍然没有完全解决,这就是我重新反弹帖子的原因。

    我做的第一件事是使用以下数据集创建一个单独的枚举类:

    public enum WeatherIcon {
        Sun, Cloud1, Cloud2, Cloud3, Rain1, Rain2, Thunder, Snow, Mist
    }
    

    然后我加了这个代码< code > final ImageView imageofWeather = root view . findviewbyid(r . id . image view 2);在我在fragment上声明textviews的地方。

    然后我添加了这个int drawableResource; //这里定义默认图标,R.drawable.default_weather_icon例如在viewModel.getWeatherDataLiveData().observe(getViewLifecycle Owner(), data -

    然后我终于添加了这个代码:

    switch (data.getWeather().get(0).getIcon()) { 
                        case WeatherIcon.Sun:
                            drawableResource = R.drawable.sun; //reference to drawable id
                            break;
                        case WeatherIcon.Cloud1:
                            drawableResource = R.drawable.broken_clouds; //reference to drawable id
                            break;
                        case WeatherIcon.Cloud2:
                            drawableResource = R.drawable.few_clouds; //reference to drawable id
                            break;
                        case WeatherIcon.Cloud3:
                            drawableResource = R.drawable.scattered_clouds; //reference to drawable id
                            break;
                        case WeatherIcon.Rain1:
                            drawableResource = R.drawable.small_rain; //reference to drawable id
                            break;
                        case WeatherIcon.Rain2:
                            drawableResource = R.drawable.shower_rain; //reference to drawable id
                            break;
                        case WeatherIcon.Thunder:
                            drawableResource = R.drawable.thunderstorm; //reference to drawable id
                            break;
                        case WeatherIcon.Snow:
                            drawableResource = R.drawable.snow; //reference to drawable id
                            break;
                        case WeatherIcon.Mist:
                            drawableResource = R.drawable.mist; //reference to drawable id
                            break;
    
    
    
            imageofWeather.setImageDrawable(drawableResource);
                }
    

    在if语句的片段下,直接访问API并显示天气图标。(相应的9个图标当前显示在第一个片段类的编号线上)。

    当前设置的问题是:

    • 对于每个案例语句,我都会收到以下错误:

    永远不会使用分配给R.drawable.sun的值(以及其余值)。

      < li >行imageofweather . setimagedrawable(drawable resource);显示此错误:

    所需类型:可绘制,提供:int

    如果有人能帮忙,我一定会很感激的。

    这是我的片段代码:

    public class FirstFragment extends Fragment {
    
        private WeatherDataViewModel viewModel;
    
        public FirstFragment() {
            // Required empty public constructor
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View rootView = inflater.inflate(R.layout.fragment_first, container, false);
            // For displaying weather data
            // all field in Java should be type in camelCase, so not current_temp but currentTemp, not Cloud_out but cloudOut
            // Capitalize name is for class not field
            final TextView current_temp = rootView.findViewById(R.id.textView10);
            final TextView current_output = rootView.findViewById(R.id.textView11);
            final TextView rise_time = rootView.findViewById(R.id.textView25);
            final TextView set_time = rootView.findViewById(R.id.textView26);
            final TextView temp_out = rootView.findViewById(R.id.textView28);
            final TextView Press_out = rootView.findViewById(R.id.textView29);
            final TextView Humid_out = rootView.findViewById(R.id.textView30);
            final TextView Ws_out = rootView.findViewById(R.id.textView33);
            final TextView Visi_out = rootView.findViewById(R.id.textView34);
            final TextView Cloud_out = rootView.findViewById(R.id.textView35);
            final ImageView imageofWeather = rootView.findViewById(R.id.imageView2);
    
    
            // Get our ViewModel instance
            viewModel = new ViewModelProvider(this).get(WeatherDataViewModel.class);
    
            // And whenever the data changes, refresh the UI
            viewModel.getWeatherDataLiveData().observe(getViewLifecycleOwner(), data -> {
    
                int drawableResource; // here define default icon for example R.drawable.default_weather_icon
    
                if (data != null) {
                    current_temp.setVisibility(View.VISIBLE);
                    current_temp.setText(data.getMain().getTemp() + " ℃"); // for that you can use strings resource and templates more in https://developer.android.com/guide/topics/resources/string-resource.html#formatting-strings
                    current_output.setVisibility(View.VISIBLE);
                    current_output.setText(data.getWeather().get(0).getDescription());
                    rise_time.setVisibility(View.VISIBLE);
                    rise_time.setText(data.getSys().getSunrise() + " ");
                    set_time.setVisibility(View.VISIBLE);
                    set_time.setText(data.getSys().getSunset() + " ");
                    temp_out.setVisibility(View.VISIBLE);
                    temp_out.setText(data.getMain().getTemp() + " ℃");
                    Press_out.setVisibility(View.VISIBLE);
                    Press_out.setText(data.getMain().getPressure() + " hpa");
                    Humid_out.setVisibility(View.VISIBLE);
                    Humid_out.setText(data.getMain().getHumidity() + " %");
                    Ws_out.setVisibility(View.VISIBLE);
                    Ws_out.setText(data.getWind().getSpeed() + " Km/h");
                    Visi_out.setVisibility(View.VISIBLE);
                    Visi_out.setText(data.getVisibility() + " m");
                    Cloud_out.setVisibility(View.VISIBLE);
                    Cloud_out.setText(data.getClouds().getAll() + " %");
    
                    // get actual weather.
                    switch (data.getWeather().get(0).getIcon()) { //or data.getWeather()[0].getIcon() i don't remember how it work in Java
                        case WeatherIcon.Sun:
                            drawableResource = R.drawable.sun; //reference to drawable id
                            break;
                        case WeatherIcon.Cloud1:
                            drawableResource = R.drawable.broken_clouds; //reference to drawable id
                            break;
                        case WeatherIcon.Cloud2:
                            drawableResource = R.drawable.few_clouds; //reference to drawable id
                            break;
                        case WeatherIcon.Cloud3:
                            drawableResource = R.drawable.scattered_clouds; //reference to drawable id
                            break;
                        case WeatherIcon.Rain1:
                            drawableResource = R.drawable.small_rain; //reference to drawable id
                            break;
                        case WeatherIcon.Rain2:
                            drawableResource = R.drawable.shower_rain; //reference to drawable id
                            break;
                        case WeatherIcon.Thunder:
                            drawableResource = R.drawable.thunderstorm; //reference to drawable id
                            break;
                        case WeatherIcon.Snow:
                            drawableResource = R.drawable.snow; //reference to drawable id
                            break;
                        case WeatherIcon.Mist:
                            drawableResource = R.drawable.mist; //reference to drawable id
                            break;
    
    
    
                        imageofWeather.setImageDrawable(drawableResource);
                    }
    
                } else {
                    Log.e("TAG", "No City found");
                    current_temp.setVisibility(View.GONE);
                    current_output.setVisibility(View.GONE);
                    rise_time.setVisibility(View.GONE);
                    set_time.setVisibility(View.GONE);
                    temp_out.setVisibility(View.GONE);
                    Press_out.setVisibility(View.GONE);
                    Humid_out.setVisibility(View.GONE);
                    Ws_out.setVisibility(View.GONE);
                    Visi_out.setVisibility(View.GONE);
                    Cloud_out.setVisibility(View.GONE);
                    Toast.makeText(requireActivity(), "No City found", Toast.LENGTH_SHORT).show();
                }
            });
    
            return rootView;
        }
    
        public void getWeatherData(String name) {
            // The ViewModel controls loading the data, so we just
            // tell it what the new name is - this kicks off loading
            // the data, which will automatically call through to
            // our observe() call when the data load completes
            viewModel.setCityName(name);
        }
    }
    

  • 共有3个答案

    苏星宇
    2023-03-14

    您必须在清单文件中创建活动别名,根据天气条件在其中设置图标。

    <?xml version="1.0" encoding="utf-8"?>
    <manifest  xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.github.erikjhordanrey.livebinding">
    
    <uses-permission android:name="android.permission.INTERNET" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
    
        <activity android:name="io.github.erikjhordanrey.livebinding.view.DcCharacterActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    
        <activity-alias
            android:name=".MainActivityAlias"
            android:enabled="false"
            android:icon="@drawable/R.drawable.sun"
            android:label="@string/app_name"
            android:roundIcon="@drawable/R.drawable.sun"
            android:targetActivity="io.github.erikjhordanrey.livebinding.view.DcCharacterActivity">
    
            <intent-filter>
    
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
    
            </intent-filter>
    
        </activity-alias>
    
        <activity-alias
            android:name=".MainActivityAlias"
            android:enabled="false"
            android:icon="@drawable/R.drawable.broken_clouds"
            android:label="@string/app_name"
            android:roundIcon="@drawable/R.drawable.broken_clouds"
            android:targetActivity="io.github.erikjhordanrey.livebinding.view.DcCharacterActivity">
    
            <intent-filter>
    
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
    
            </intent-filter>
    
        </activity-alias>
    
        <activity-alias
            android:name=".MainActivityAlias"
            android:enabled="false"
            android:icon="@drawable/R.drawable.few_clouds"
            android:label="@string/app_name"
            android:roundIcon="@drawable/R.drawable.few_clouds"
            android:targetActivity="io.github.erikjhordanrey.livebinding.view.DcCharacterActivity">
    
            <intent-filter>
    
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
    
            </intent-filter>
    
        </activity-alias>
    
        <!--and so on....-->
    </application>
    
    </manifest>
    

    在主活动文件中,您必须根据天气状况更改图标。

    private void newicon() {
          
          // enable old icon
        PackageManager manager=getPackageManager();
        manager.setComponentEnabledSetting(new ComponentName(MainActivity.this,"com.prepare.makedirectory.MainActivity")
                ,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,PackageManager.DONT_KILL_APP);
          
          // enable new icon
        manager.setComponentEnabledSetting(new ComponentName(MainActivity.this,"com.prepare.makedirectory.MainActivityAlias")
                ,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
        Toast.makeText(MainActivity.this,"Enable New Icon" ,Toast.LENGTH_LONG).show();
    }
    

    您可以在此链接中找到整篇文章:https://www.geeksforgeeks.org/how-to-change-app-icon-of-android-programmatically-in-android/

    韦安怡
    2023-03-14
    匿名用户

    行imageofweather . setimagedrawable(drawable resource);显示此错误:

    Required type: Drawable, Provided: int
    

    这意味着setImageDrawable()需要(期望)一个Drawable参数,但提供的(找到的)参数是int

    要解决此问题,请使用 setImageResource() 代替,它采用 int 可绘制资源而不是可绘制对象

    对于每个案例语句,我都会收到以下错误:

    The value R.drawable.sun(and the rest) assigned to 'drawableResource' is never used.
    

    这是由于前一个错误而引发的,因为它认为drawableResource未被setImageDrawable()的行使用,因此它警告您您为它分配了一个值,但从未使用过它。

    应通过修复第一个警告来修复此警告;不过,我建议用私有构造函数重写< code>enum,该构造函数接受< code>int drawable资源值,它将处理switch语句,而不是让片段来处理。

    新枚举:

    public enum WeatherIcon {
    
        Sun(R.drawable.sun),
        Cloud1(R.drawable.broken_clouds),
        Cloud2(R.drawable.few_clouds),
        Cloud3(R.drawable.scattered_clouds),
        Rain1(R.drawable.small_rain),
        Rain2(R.drawable.shower_rain),
        Thunder(R.drawable.thunderstorm),
        Snow(R.drawable.snow),
        Mist(R.drawable.mist);
    
        private int drawable;
    
        WeatherIcon(int drawable) {
            this.drawable = drawable;
        }
    
        public int getDrawable() {
            return drawable;
        }
    
    }
    

    然后,您可以通过使用枚举的getDrawable()方法来获取可绘制的内容,而不是片段中的switch语句,如下所示:

    WeatherIcon icon = data.getWeather().get(0).getIcon();
    int drawableResource = icon.getDrawable();
    imageofWeather.setImageResource(drawableResource);
    

    马丰
    2023-03-14

    也许可以这样试试:

    1. 创建一个带有枚举的天气类,指定要显示的图标。
    2. 下载数据后,转换为创建的类
    3. 一个单独的函数,它将决定给定枚举的显示内容

    编辑:

    public class Example{
      // add to your definition
      private WeaterIcon icon;
    
      public WeaterIcon getIcon() {
          return icon;
      }
    
      public void setIcon(WeaterIcon icon) {
          this.icon = icon;
      }
    }
    
    enum WeaterIcon {
      SUN, FROG, //type all what want
    }
    

    在创建视图中

    //there are yor reference to xml object
        final ImageView imageOfWeather = rootView.findViewById(R.id.imageView); // add this reference
    

    并选择右图标

    int drawableResource; // here define default icon or not
                switch(data.getIcon()) {
                    case WeaterIcon.SUN:
                        drawableResource = R.drawable.sun_icon //reference to drawable id
                        break;
                    case WeaterIcon.FROG:
                        drawableResource = R.drawable.frog_icon//reference to drawable id
                        break;
                    //add all
                }
    
    
                imageOfWeather.setImageDrawable(drawableResource);
    
     类似资料: