1、在配置文件里写的,在垂直线性布局里添加一个文本view和一个按钮。
2、下面是使用代码的方式, *** 作相对比较繁琐。有种使用LayoutInflater.from(this).inflate(resource, root)会比较方便点。
RelativeLayout layout = new RelativeLayout(this)
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT))
TextView name = new TextView(this)name.setText("您好")
android.widget.RelativeLayout.LayoutParams layoutParams = new android.widget.RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE)
layout.addView(name)
首先在你的helloworld程序对应的layout配置文件(res/layout/下的XXX.xml文件)中添加一个按钮,具体代码如下<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:id="@+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- 下面这段就是添加的button -->
<Button android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="change background" />
</LinearLayout>
然后在你的继承Activity类的java类中添加按钮的事件监听以及事件处理,代码如下:
public class 你的helloworld类名 extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.你的layout文件名)
//下面的代码用于为按钮注册一个监听
findViewById(R.id.frame_layout).setOnClickListener(new OnClickListener() {
//下面的代码用于处理按钮点击后的事件
public void onClick(View v) {
//下面的代码用于使背景变色
findViewById(R.id.layout).setBackgroundColor(Color.BLUE)
}
})
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)