先来一下实体效果图片:
点击 HELLO WORLD,不断产生 button按钮,在最下方。
代码 如下:
public class MainActivity extends Activity {
private ViewGroup viewGroup;
private int countId = 100;
private SpecialCustomView specialCustomView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.layout );
viewGroup = (ViewGroup) findViewById( R.id.container );
specialCustomView = new SpecialCustomView();
Button button = specialCustomView.addView( this , countId );
countId ++;
viewGroup.addView( button );
setContentView( viewGroup );
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
// 添加视图 组件
Button button = specialCustomView.addView( MainActivity.this , countId );
countId ++;
viewGroup.addView( button );
setContentView( viewGroup );
}
});
}
public class SpecialCustomView{
public Button addView( Context context , int countId ){
Button button = new Button( context );
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// 设置位置
if( countId == 100)
params.addRule( RelativeLayout.BELOW , R.id.topic);
else
params.addRule( RelativeLayout.BELOW , countId-1 );
button.setLayoutParams(params);
button.setBackgroundColor(Color.RED);
button.setText( "第" + countId + "个button" );
button.setId( countId ++ );
return button;
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container">
<!-- 置顶内容设置的视图 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/topic">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="置顶内容的标题"
android:textSize="24sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="置顶内容下面的内容"
android:textSize="14sp"/>
</LinearLayout>
</RelativeLayout>
为什么是使用 Java代码产生 视图?
目前就是我正在做 一个页面展示的功能,由于展示内容 就是 百度app首页新闻消息一样,共同点太多,所以采用了LinearLayout + ListView 产生视图内容,但是这样如果涉及到图片,视屏方面的话,就有点问题了。
Android 请求数据方面全部是异步操作,所以一旦 视图渲染完成,可能当图片渲染到了的时候,找不到对应的视图了,因为LinearLayout + ListView产生的视图,全部一模一样的,甚至 id 值。所以无法再次通过id进行页面修改。所以就是使用到Java代码产生视图,通过自定义视图id,可以修改界面。
相关函数以及参数解析:
countId 表示下一个button 的id值
表示 视图占据的宽度和高度 MATCH_PARENT 占满,WRAP_CONTENT 内容而定
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
第一个参数:表示相对于视图的什么位置,第二个参数:表示相对的视图
params.addRule( RelativeLayout.BELOW , R.id.topic);
获取 RelativeLayout 布局的容器:在这里是获取整个layout.xml文件里面的内容
viewGroup = (ViewGroup) findViewById( R.id.container );