android studio第一个项目代码
时间: 2024-05-11 08:12:44 浏览: 10
当你创建一个新的Android Studio项目时,会自动生成一些初始代码,其中包括:
1. MainActivity.java:这是应用程序的主要活动,也是应用程序的入口点。它包含了一个onCreate()方法,在该方法中你可以初始化应用程序的UI界面和其他一些操作。
2. activity_main.xml:这是默认的布局文件,用于显示MainActivity中的UI界面。在这个文件中你可以定义应用程序的UI界面布局、控件、样式和属性等。
3. AndroidManifest.xml:这是应用程序的清单文件,它包含了应用程序的名称、图标、版本号、权限等信息,同时也指定了应用程序的活动和服务等。
下面是MainActivity.java的代码示例:
```
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 在这里添加你的代码
}
}
```
以上代码中,MainActivity继承自AppCompatActivity类,并覆盖了onCreate()方法。在该方法中,我们调用setContentView()方法来加载activity_main.xml布局文件,并在该方法中添加你的代码。
下面是activity_main.xml的代码示例:
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="30sp"
android:gravity="center"/>
</LinearLayout>
```
以上代码中,我们使用了一个LinearLayout布局容器,并在其中添加了一个TextView控件来显示“Hello World!”文本。你可以通过修改TextView控件的属性或者添加其他控件来自定义你的应用程序UI界面。