安卓最常见的形式是代码和图形界面分开编程(Activity和Layout)
也可以采用在代码中手动创建容器和控件的方式,给出一份基本Demo
package com.test.codeview;
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//创建容器
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
//对容器类创建后再设置Layout属性会报错
//linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
//ViewGroup.LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
//创建一个TextView控件
TextView show = new TextView(this);
show.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
show.setText(R.string.app_name);
//创建一个Button
Button bn = new Button(this);
bn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
bn.setOnClickListener(view -> {
show.setText(""+ new java.util.Date());
});
//将TextView和Button都添加到容器中
linearLayout.addView(show);
linearLayout.addView(bn);
}
}