在Android上创建应用程序时,必然要创建界面,而界面是由各种各样的Android控件组成的。

那么在界面设计中,有两种方式添加控件。一种是静态的,一种是动态的。

1、 先说第一种静态创建。

需要在layout目录下创建布局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:layout_width="match_parent"    android:layout_height="match_parent"     >    <Button        android:id="@+id/button_download"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/download"        /></LinearLayout>

这个布局很简单,只是在界面上添加了一个按钮,显示如图所示:

在使用该界面的activity上,可以通过R类来取得xml文件中的控件。

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_download);setupViews();mDownloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);}    private void setupViews() {    Button button = (Button) findViewById(R.id.button_download);    button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {startDownload(strUrl);}        });    }

这样就可以在代码中使用该Button控件了。这种方式将界面设计的布局和代码分离。

2、第二种方式是动态创建控件。

也就是说不用xml布局文件,而是完全在代码中创建控件。由xml布局的东东其实都可以在代码中实现。实例代码如下:

    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);                setupViews();    }        private void setupViews() {    LinearLayout linearLayout = new LinearLayout(this);    linearLayout.setOrientation(LinearLayout.VERTICAL);      //add button1    Button button1 = new Button(this);    button1.setText("Download");    button1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {Intent intent = new Intent();intent.setClass(getApplicationContext(), DownloadActivity.class);startActivity(intent);}        });    linearLayout.addView(button1);        //add button2    Button button2 = new Button(this);    button2.setText("AlertDialog");    button2.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {Intent intent = new Intent();intent.setClass(getApplicationContext(), AlertDialogActivity.class);startActivity(intent);}        });    linearLayout.addView(button2);        setContentView(linearLayout);    }

这种方法虽然没有将布局文件写在xml中这样清晰,但是有些时候却很方便、简单。也会用到的。

以上示例代码可下载,地址为:https://github.com/tingzi/AndroidExample.git

更多相关文章

  1. 【Android(安卓)开发】:UI控件之 ImageView 实现图片旋转和缩放功
  2. android手机短信发送
  3. Android布局之线性布局
  4. Android中View的绘制过程 onMeasure方法简述
  5. tablelayout布局内容居中的问题
  6. android之AIDL跨进程通信详解
  7. Android中ListView动态加载数据
  8. 用Tasker转发Android上收到的短信至Telegram
  9. 很通俗易懂的概念Activity,Window,DecorView

随机推荐

  1. android之简单数据存储Preference
  2. Android常用UI
  3. Android(安卓)Permission访问权限许可
  4. android之JSON解析(一)
  5. android bitmap drawable 互转
  6. android手机内部存储空间和外部存储空间
  7. mono for android之文件系统与应用程序首
  8. Android(安卓)记住密码和自动登录界面的
  9. RSA算法 Android(安卓)JAVA C#互通
  10. 【Android(安卓)开发】:Android中普通按钮