Android界面布局编写方法
浏览:373 次

1.在XML文件中编写布局Android可以使用XML布局文件来控制界面布局,从而有效地将界面中的布局代码与Java代码隔离开来,使程序的结构更加清晰。因此,大多数Android程序都使用这种方法来编写布局。如前所述,布局文件通常放置在res/layout文件夹中。我们可以将布局写入此文件夹的XML文件中。以下是actIvity_ main的布局代码。xml如下所示。
xml版本=“1.0”编码=“utf-8”?>;
;xmlns:tools=“https://schemas.android.com/tools" ; ;android:layout_width=“匹配父项” ;android:layout_ height=“match_ parent” ;工具:context=“.MainActivity”>;  书信电报;文本框  nbsp; ;android:layout_ width=“wrap_内容”  nbsp; ;android:layout_ height=“wrap _ content”  nbsp; ;android:text=“使用XML布局文件控制UI”  nbsp; ;android:textColor=“#ff0000”  nbsp; ;android:textSize=“18sp”  nbsp; ;android:layout_centerInParent=“true”  nbsp; ;/>; protected void onCreate(捆绑savedInstanceState){ ;super.onCreate(savedInstanceState); ;setContentView(R.layout.activity_main);//呼叫活动_主 } 在上面的代码中,定义了相对布局RelativeLayout,并在布局中定义了TextView控件。其中,Relative layout继承自ViewGroup,TextView继承自veh。 Android程序的布局不仅可以用XML布局文件编写,也可以用Java代码编写。在Android中,所有布局和控件对象都可以通过new关键字创建,创建的View控件可以添加到ViewGroup布局中,以便视图控件可以显示在布局界面中。接下来,我们将使用XML布局文件使用Java代码重写布局。重写的示例 代码如下: 包com.example.miapplication; import androidx.appcompat.app.AppCompatActivity; import android.graphics.Color; import android.os.Bundle; import android.widget.RelativeLayout; import android.widget.TextView; 公共类MainActivity扩展AppCompatActivity{ @推翻 ;protected void onCreate(捆绑savedInstanceState){  nbsp; ;super.onCreate(savedInstanceState);  nbsp; ;RelativeLayout RelativeLayout=新RelativeLlayout(此);  nbsp; ;相对布局。LayoutParams params=新RelativeLayout.LayoutParams(RelativeLlayout.Layout params.WRAP_CONTENT,RelativeLLayout.LayoutParameters.WRAP_CONTENT);  nbsp; ;//addRule参数对应于RelativeLayout XML布局的属性  nbsp; ;params.addRule(RelativeLayout.CENTER_IN_PARENT); ; ; ;//设置中心  nbsp; ;TextView TextView=新建TextView(此); ; ; ;//创建文本视图控件  nbsp; ;text查看。setText(“使用Java实现界面布局”) ; ; ; ; ;//设置TextView的文本内容  nbsp; ;textView.setTextColor(颜色.RED); ; ; ; ; ; ; ; ; ; ;//设置TextView的文本颜色  nbsp; ;text查看。setTextSize(18); ; ; ; ; ; ; ; ; ; ; ; ; ; ;//设置TextView的文本大小  nbsp; ;//添加T
2.用Java代码编写布局

