[Android]应用界面创建控件的两种方式
16lz
2021-01-26
在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
更多相关文章
- 【Android(安卓)开发】:UI控件之 ImageView 实现图片旋转和缩放功
- android手机短信发送
- Android布局之线性布局
- Android中View的绘制过程 onMeasure方法简述
- tablelayout布局内容居中的问题
- android之AIDL跨进程通信详解
- Android中ListView动态加载数据
- 用Tasker转发Android上收到的短信至Telegram
- 很通俗易懂的概念Activity,Window,DecorView