package com.example.helloworld01;//包名
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 定义线性布局
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
// 定义相对布局
RelativeLayout relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundColor(Color.GRAY);
// 定义两个按钮
Button button1 = new Button(this);
button1.setText("按钮1");
Button button2 = new Button(this);
button2.setText("按钮2");
// 定义列表控件
ListView listView = new ListView(this);
listView.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_expandable_list_item_1, getData()));
// 想要按钮2在右边需要定义布局参数LayoutParams
RelativeLayout.LayoutParams rLayoutParams = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// 定义规则:在相对布局右边
rLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
// 将按钮1加入相对布局
relativeLayout.addView(button1);
// 将按钮2和布局参数加入相对布局
relativeLayout.addView(button2, rLayoutParams);
// 将相对布局加入线性布局
linearLayout.addView(relativeLayout);
// 将列表加入线性布局
linearLayout.addView(listView);
setContentView(linearLayout);
}
private List getData() {
List liStrings = new ArrayList();
for (int i = 0; i < 9; i++) {
liStrings.add("列表"+i);
}
return liStrings;
}
}
结果: