当前位置: 代码迷 >> Android >> 怎么用代码来改变button的位置
  详细解决方案

怎么用代码来改变button的位置

热度:107   发布时间:2016-05-01 21:33:07.0
如何用代码来改变button的位置
我想要把用new写出的button动态的安排在listview下(其位置随listview大小改变而改变,但是紧挨在listview下面),使用AbsoluteLayout.LayoutParams来定义button的位置,但是很可惜的是,每次button都在左上角和listview重叠

求教:如何用代码来改变button的位置

------解决方案--------------------
android只有等create后,才计算所有的控件布局.
------解决方案--------------------
ListView可以通过addFooterView添加控件,用下面代码
public class MyListViewActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Button button = new Button(this);
button.setText("Change To MyListView2");

final ListView listview = new ListView(this);
LinearLayout layout = new LinearLayout(MyListViewActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.addView(button);
listview.addFooterView(layout);
listview.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, getData()));
addContentView(listview,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0, 0));





ViewTreeObserver vto = listview.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
public void onGlobalLayout(){
int left =listview.getLeft();
int top = listview.getTop()+listview.getHeight();
Log.i("left", (new Integer(left)).toString());
Log.i("top", (new Integer(top)).toString());
//AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, left, top);
//addContentView(button, params);
listview.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});


button.setOnClickListener(new OnClickListener(){
public void onClick(View view){
Intent intent = new Intent();
intent.setClass(MyListViewActivity.this, MyListViewActivity2.class);
startActivity(intent);
}
});
}

private List<String> getData(){

List<String> data = new ArrayList<String>();
data.add("测试数据1");
data.add("测试数据2");
data.add("测试数据3");
data.add("测试数据4");
data.add("测试数据5");
data.add("测试数据6");
data.add("测试数据7");
data.add("测试数据8");
data.add("测试数据9");
data.add("测试数据10");
data.add("测试数据11");

return data;
}
}
  相关解决方案