请用Java语言编写天气预报的Android程序
时间: 2023-03-02 12:04:20 浏览: 58
好的,以下是一个简单的使用Java语言编写的天气预报的Android程序的示例代码:
```
public class MainActivity extends AppCompatActivity {
private TextView cityText;
private TextView conditionText;
private TextView temperatureText;
private WeatherService weatherService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityText = findViewById(R.id.city_text);
conditionText = findViewById(R.id.condition_text);
temperatureText = findViewById(R.id.temperature_text);
weatherService = new WeatherService();
Button getWeatherButton = findViewById(R.id.get_weather_button);
getWeatherButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String city = cityText.getText().toString();
Weather weather = weatherService.getWeather(city);
if (weather != null) {
conditionText.setText(weather.getCondition());
temperatureText.setText(String.valueOf(weather.getTemperature()) + "°C");
} else {
Toast.makeText(MainActivity.this, "无法获取天气信息,请检查网络连接", Toast.LENGTH_SHORT).show();
}
}
});
}
}
public class WeatherService {
public Weather getWeather(String city) {
// TODO: 调用天气API获取天气信息,这里假设返回一个Weather对象
return new Weather("晴", 20);
}
}
public class Weather {
private String condition;
private int temperature;
public Weather(String condition, int temperature) {
this.condition = condition;
this.temperature = temperature;
}
public String getCondition() {
return condition;
}
public int getTemperature() {
return temperature;
}
}
```
以上代码中,`MainActivity`是应用的主要Activity,用于处理用户交互和显示天气信息。`WeatherService`是用于获取天气信息的服务类,它可以调用天气API获取实际的天气信息。`Weather`是一个简单的POJO类,用于表示天气信息。在`MainActivity`的`onClick`方法中,我们首先从输入框中获取城市名称,然后调用`WeatherService`获取天气信息,最后将天气状况和温度显示在相应的文本框中。如果无法获取天气信息,我们将显示一个简短的Toast提示用户。请注意,这只是一个简单的示例,实际上需要根据具体的天气API来编写相应的代码。