使用java代碼添加控制項

來源:互聯網
上載者:User

標籤:

平時多習慣於採用xml檔案來添加布局和控制項,採用java代碼在activity中添加控制項也是一種方式,下面簡單舉兩個例子:

1、addContentView

addContentView作用類似於setContentView()來為activity初始化布局:

 1 public class MainActivity extends Activity { 2  3     @Override 4     protected void onCreate(Bundle savedInstanceState) { 5         super.onCreate(savedInstanceState); 6         //setContentView(R.layout.activity_main); 7         TextView tv=new TextView(getApplicationContext()); 8         tv.setText("hello world1"); 9         tv.setBackgroundColor(Color.GRAY);10         tv.setGravity(Gravity.CENTER);11         int x=LayoutParams.MATCH_PARENT;12         int y=LayoutParams.WRAP_CONTENT;13         LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(x,y);14         this.addContentView(tv, params);15         16         17     }18 }

在java代碼中添加控制項同樣可以設定各種屬性,如例中setText,setBackgroundColor等。效果:

2、addView

addView在父控制項的基礎上添加子控制項,作用類似於在xml檔案中添加一個控制項:

public class addViewActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        LinearLayout ll = (LinearLayout) findViewById(R.id.ll);        TextView tv = new TextView(getApplicationContext());        tv.setText("hello world2");        tv.setBackgroundColor(Color.GRAY);        tv.setGravity(Gravity.CENTER);        ll.addView(tv);    }}

xml檔案:

1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"2     xmlns:tools="http://schemas.android.com/tools"3     android:id="@+id/ll"4     android:layout_width="match_parent"5     android:layout_height="wrap_content"6     android:orientation="vertical" >7 8 </LinearLayout>

同樣可以添加控制項的各種屬性。效果:

 

 

 


 

使用java代碼添加控制項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.