1.概览
本文记录了一个基本的android的运行过程,如何写hello请参考ref,这里只是记录基础过程:
1.各种各样的layout.xml文件中写好了view,布局, 按钮等要的显示控件,安卓app运行的时候,这个xml文件就会被生成对应的view对象
2.安卓运行的入口main文件是MainActivity.java, 程序入口main函数是onCreate()
3.在onCreate()中使用setContentView()设置显示的layout.xml,就会加载这个layout对应的对象进行显示
4.每个控件都有一个id,通过使用view.findViewById(),可以找到对应的空间对象进行操作,如果前面不加"view."则调用的是当前Activity的该方法,其会先去当前windows获取当前view,再通过当前view去执行findViewById()
2.正文
通过ref中的2.Android Hello World 实例可以看到,其创建了一个文件 activity_main.xml, 其中定义了一个TextView, 上面的Text放了"hello_world",该控件的id为"hello_world"
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
android:id="@+id/hello_world"
tools:context=".MainActivity" />
</RelativeLayout>
然后在 MainActivity.java的onCreate() 中可以看到 setContentView() 设置了要显示的为 R.layout.activity_main(所有的layout资源都以id的形式放在R中进行管理), 通过findViewById()找到id为hello_world的TextView, 最后调用tv.setText()设置Text
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //设置要显示的layout
TextView tv = findViewById(R.id.hello_world); //找到该控件
tv.setText("a new hello world"); //设置text
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}