基于Android代码实现常用布局

2019-12-10 19:54:32于丽

大家在日常中经常见到用xml文件实现android常用布局,但是大家知道如何用代码实现呢?使用代码实现可以帮助我们学习sdk api,所以小编把我日常整理些关于android常用布局代码实现分享给大家

关于 android 常用布局,利用 XML 文件实现已经有很多的实例了。但如何利用代码实现呢?当然利用代码实现没有太大的必要,也是不提倡的,但我觉得利用代码实现这些布局,可以更好的了解 SDK API ,所以在此也整理一些,和大家分享一下。

首先看一下,布局所对应的类的 API 继承图:

基于Android代码实现常用布局

android常用布局的代码实现所有的布局都会对应相关的类,这些类都是继承自 android.view.ViewGroup 类的。而 LinearLayout,RelativeLayout 都是在 android.widget 包里的。另外,TableLayout 是继承自 LinearLayout.

下面直接贴代码了。

 

 
  1. // 利用代码设置 线性布局  private void setLinearLayout(){ 
  2. LinearLayout llayout = new LinearLayout(this);  llayout.setOrientation(LinearLayout.VERTICAL); // 设置线性布局的排列方式 
  3. TextView textView = new TextView(this);  textView.setText("代码实现的线性布局"); 
  4. textView.setTextColor(Color.RED);  textView.setGravity(Gravity.CENTER); // 设置文本内容的对齐方式 
  5. LinearLayout.LayoutParams ll_lpara = new LinearLayout.LayoutParams(MP,WC);  // ll_lpara.gravity = Gravity.CENTER_HORIZONTAL; // 设置控件在布局中的对齐方式 
  6. llayout.addView(textView,ll_lpara);  Button btn = new Button(this); 
  7. btn.setText("按钮");  llayout.addView(btn,ll_lpara); // 按指定属性添加控件 
  8. setContentView(llayout);   }