View是所有控件类的父类
在activity_main.xml布局文件中,在<textView />布局文件中加入android:id="@+id/textView"后就会在R.java中生成id
textView = (TextView)findViewById(R.id.textView);会通过id把控件的对象给找出来(得到控件的对象),之所以要向下转型是因为findViewById返回的都是View类型的对象,而通过R.id.textView找到的对象是TextView类型的对象,所以TextView对象先是向上转型后是向下转型。
<LinearLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF0000"
android:text="hello_world" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button"/>
</LinearLayout>
控件既可以通过XML布局文件代码来设置控件的属性,也可以在MainActivity.java通过java代码来获得控件对象,并调用这个对象的方法来设置这个对象的属性。在布局文件里可以做到的,在代码中一般也可以做到,反过来也一样。
Button控件可以用多个监听器,比如来响应单击及长点击,
package com.example.rain;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int count = 0;
private TextView textView;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
textView.setBackgroundColor(Color.RED);
textView.setText("hello Rain!"); //虽然之前在XML中已经设置过文字,但是后来的会把它给覆盖,因为这个代码在setContentView后执行
button = (Button)findViewById(R.id.button);
ButtonListener buttonListener = new ButtonListener();
button.setOnClickListener(buttonListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class ButtonListener implements OnClickListener{
@Override
public void onClick(View arg0) {
count++;
textView.setText(count + "");
}
}
}
上述代码达到了单击button来递增改变数字的效果