天气预报Android studio 代码
时间: 2023-09-16 15:16:21 浏览: 240
以下是一个简单的天气预报 Android Studio 代码示例:
1. 创建一个新的 Android Studio 项目,并在布局文件中添加以下元素:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/locationTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Location" />
<TextView
android:id="@+id/temperatureTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="50sp"
android:textStyle="bold"
android:layout_below="@+id/locationTextView"
android:layout_centerHorizontal="true"
android:text="Temperature" />
<ImageView
android:id="@+id/weatherImageView"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_below="@+id/temperatureTextView"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher_foreground" />
</RelativeLayout>
```
2. 在 MainActivity.java 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private TextView locationTextView;
private TextView temperatureTextView;
private ImageView weatherImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationTextView = findViewById(R.id.locationTextView);
temperatureTextView = findViewById(R.id.temperatureTextView);
weatherImageView = findViewById(R.id.weatherImageView);
WeatherAsyncTask weatherAsyncTask = new WeatherAsyncTask();
weatherAsyncTask.execute("New York");
}
private class WeatherAsyncTask extends AsyncTask<String, Void, Weather> {
@Override
protected Weather doInBackground(String... strings) {
String location = strings[0];
Weather weather = new Weather();
weather.setLocation(location);
weather.setTemperature("15C");
weather.setWeatherIcon(R.drawable.ic_launcher_foreground);
return weather;
}
@Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
locationTextView.setText(weather.getLocation());
temperatureTextView.setText(weather.getTemperature());
weatherImageView.setImageResource(weather.getWeatherIcon());
}
}
}
```
3. 创建一个 Weather.java 类,用于存储天气信息:
```java
public class Weather {
private String location;
private String temperature;
private int weatherIcon;
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getTemperature() {
return temperature;
}
public void setTemperature(String temperature) {
this.temperature = temperature;
}
public int getWeatherIcon() {
return weatherIcon;
}
public void setWeatherIcon(int weatherIcon) {
this.weatherIcon = weatherIcon;
}
}
```
这是一个很简单的示例,仅用于演示如何在 Android Studio 中创建天气预报应用程序。实际开发中,您需要使用 API 来获取实时天气数据,并在 UI 中显示它。
阅读全文