Android——UI和View——控制方式
控制方式
只用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" tools:context="com.example.chenshuai.test322.MainActivity" android:orientation="vertical"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮一"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按钮二" android:id="@+id/button"/> </LinearLayout>
只用java代码实现
package com.example.chenshuai.test322; import android.os.Bundle; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import android.widget.Button; import android.widget.LinearLayout; /** * Created by chenshuai on 2016/3/22. */ public class Activity1 extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //创建布局管理器 线性布局 将线性布局放入Activity里 LinearLayout linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setLayoutParams(new DrawerLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); Button button = new Button(this); button.setText("按钮三"); button.setLayoutParams(new DrawerLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); //把View(按钮)放到布局(LinearLayout)里 linearLayout.addView(button); //关联布局管理器 setContentView(linearLayout); } }
二者结合使用
将用xml建的按钮一的Text内容用java代码改变
package com.example.chenshuai.test322; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button)findViewById(R.id.button2); button.setText("新按钮名称"); } }