其实在Android中,使用控件除了在layout下的布局文件中实现之外,我们还可以通过在java文件中完全通过编码来实现,只不过完全使用编码的方式来驾驭我们的控件是不可取的,因为这增加了代码量,对外阅读不是太友好,一般的做法是在布局文件中布局某个控件,并使用id来标识,然后在编码中通过提取该id的方法来控制,下面将介绍之~~
文件目录如下:
动作一:
创建TextViewTest1工程;
动作二:
修改布局文件,在这边我增加了一个名字为id为myTextView的TextView,修改见横线部分;
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
- <TextView
- android:id="@+id/myTextView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
动作三:
修改我们的TextViewTest1Activity.java文件,在这边我们下述函数:
- // 声明TextView对象mTextView
- private TextView mTextView;
- // 将名为myTextView赋给mTextView
- mTextView = (TextView) findViewById(R.id.myTextView);
来获得我们在布局文件中定义的myTextView。
完整代码如下:
- package org.ourunix.android.textviewtest1;
- import android.app.Activity;
- import android.graphics.Color;
- import android.os.Bundle;
- import android.widget.TextView;
- public class TextViewTest1Activity extends Activity {
- // 声明TextView对象mTextView
- private TextView mTextView;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- // 将名为myTextView赋给mTextView
- mTextView = (TextView) findViewById(R.id.myTextView);
- // 设置mTextView的文字
- mTextView.setText("这是我的TextView");
- // 设置字体大小
- mTextView.setTextSize(20);
- // 设置背景
- mTextView.setBackgroundColor(Color.BLUE);
- // 设置字体颜色
- mTextView.setTextColor(Color.RED);
- }
- }
动作四:
运行TextViewTest1,效果如下: