参考原文在https://blog.csdn.net/harvic880925/article/details/18042183#
下面我是我修改的一段测试代码
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ProgressBar; import android.graphics.Color; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast;
public void addC(View view){ // 获取需要被添加控件的Linear布局(方法二) setContentView(R.layout.activity_main); final LinearLayout lin = (LinearLayout) findViewById(R.id.mainLinearLayout); // 添加一个LinearLayout布局,设置成layout_width:wrap_content;layout_height:wrap_content; LinearLayout layout = new LinearLayout(this); // 线性布局方式 layout.setOrientation(LinearLayout.HORIZONTAL); // layout.setBackgroundColor(0xff00ffff); LinearLayout.LayoutParams LP_MM = new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layout.setLayoutParams(LP_MM); //添加一个ImageView,设置成layout_width:50;layout_height:50; ImageView imageView = new ImageView(this); imageView.setBackgroundResource(R.mipmap.ic_logo); LinearLayout.LayoutParams PARA = new LinearLayout.LayoutParams(50, 50);// imageView.setLayoutParams(PARA); layout.addView(imageView); //添加一个TextView,设置成layout_width:wrap_content;layout_height:wrap_content; TextView tv = new TextView(this); // 普通聊天对话 tv.setText("我和猫猫是新添加的"); tv.setBackgroundColor(Color.GRAY); LinearLayout.LayoutParams LP_WW = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); tv.setLayoutParams(LP_WW); layout.addView(tv); //将动态增加的布局添加到当前布局中; lin.addView(layout); setContentView(lin); // 向动态添加的imageView,添加点击响应 imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Toast.makeText(MainActivity.this, "点击了图片", Toast.LENGTH_SHORT) .show(); } });
发表评论