动态添加一个视图及其布局属性(要掌握)
Posted 挣脱生命的束缚...
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态添加一个视图及其布局属性(要掌握)相关的知识,希望对你有一定的参考价值。
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.admin.myapplication30.FrameActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/btn_add_frame" android:gravity="center" android:text="添加视图" android:textColor="#000000" android:textSize="17sp"/> <FrameLayout android:id="@+id/fl_frame" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:foreground="@mipmap/ic_launcher" android:foregroundGravity="top|center_horizontal"> </FrameLayout> </LinearLayout> </android.support.constraint.ConstraintLayout>
package com.admin.myapplication30; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.LinearLayout; public class FrameActivity extends AppCompatActivity implements View.OnClickListener { private FrameLayout fl_content; private int[] mColorArray = { Color.BLACK, Color.WHITE, Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA, Color.GRAY, Color.DKGRAY }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_frame); fl_content = (FrameLayout) findViewById(R.id.fl_frame); findViewById(R.id.btn_add_frame).setOnClickListener(this); } @Override public void onClick(View v) { if (v.getId() == R.id.btn_add_frame) { int random = (int) (Math.random()*10 % 10); View vv = new View(this); vv.setBackgroundColor(mColorArray[random]); LinearLayout.LayoutParams ll_params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, (random+1)*50); vv.setLayoutParams(ll_params); vv.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View vvv) { fl_content.removeView(vvv); return true; } }); fl_content.addView(vv); } } }
以上是关于动态添加一个视图及其布局属性(要掌握)的主要内容,如果未能解决你的问题,请参考以下文章