转自:http://blog.sina.com.cn/s/blog_7fb706250100yjiw.html
好久不写博客了,因为生活的种种呀,今天记录下自己的学习心得,如何动态改变view在布局中的位置和大小。在开发中,系统自带的许多Layout不能满足需要,所以要自己自定义layout,当然AbsoluteLayout已经被废弃不建议使用了。
我想实现的功能是:
1.自定义Layout实现放入其中的组件可以动态改变位置和大小。
自定义CustomLayout.java
package com.wxq.layout;
import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
//import android.widget.AbsoluteLayout;
public class CustomLayout extends ViewGroup {
public CustomLayout(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public CustomLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
}
}
main.xml:
android:layout_height="fill_parent"
android:orientation="vertical" >
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
/>
其中只有自己的布局,其他的View要自己手动添加。
主程序:
TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = getLayoutInflater();
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.main, null);
mTextView = new TextView(this);
mTextView.setText("wxq say hello!");
mTextView.setTextColor(Color.WHITE);
mTextView.setBackgroundColor(Color.RED);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(100, 100);
CustomLayout cLayout = (CustomLayout) linearLayout.findViewById(R.id.cLayout);
cLayout.setBackgroundColor(Color.BLUE);
cLayout.addView(mTextView,layoutParams);
mTextView.layout(20, 20, 150+20, 150+20);
Log.d("wxq", "mTextView = " +mTextView + ",and parent is:"+mTextView.getParent());
mTextView.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Log.d("wxq", "textW = "+mTextView.getMeasuredWidth()+ ",H = "+mTextView.getMeasuredHeight());
}
});
setContentView(linearLayout);
}