Android动态生成Relativelayout + button
程序员文章站
2022-06-29 13:37:24
...
要求:输入每行btn个数,输出一共200个btn。
直接上代码,参考了csdn上的博客 android:动态创建多个按钮
不需要任何XML文件即可显示出btn。
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
private EditText editNum;
private Button addbtn;
DisplayMetrics dm = new DisplayMetrics();
//MainActivity().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
Button[] btt = new Button[205];
//RelativeLayout layout = new RelativeLayout(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final RelativeLayout rlayout = new RelativeLayout(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT );
RelativeLayout.LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_LEFT );
rlayout.setLayoutParams(layoutParams);
editNum = new EditText(MainActivity.this);
editNum.setHint("请输入个数");
editNum.setLayoutParams(layoutParams2);
addbtn = new Button(MainActivity.this);
addbtn.setWidth(100);
addbtn.setHeight(40);
addbtn.setText("add");
addbtn.setLayoutParams(layoutParams);
rlayout.addView(editNum);
rlayout.addView(addbtn);
addbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int linenum = Integer.parseInt(editNum.getText().toString());
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
Button Btn[] = new Button[205];
int j = -1;
for (int i=0; i<200; i++) {
Btn[i]=new Button(MainActivity.this);
Btn[i].setId(i);
Btn[i].setText("B"+i);
RelativeLayout.LayoutParams btParams = new RelativeLayout.LayoutParams ((width-50)/linenum,120);
if (i%linenum == 0) {
j++;
}
btParams.leftMargin = 10+ ((width-50)/linenum+10)*(i%linenum);
btParams.topMargin = 120 + 120*j;
rlayout.addView(Btn[i],btParams);
}
}
});
setContentView(rlayout);
}
}
运行效果
参考博文:https://blog.csdn.net/lihengfang/article/details/8204238
推荐阅读
-
[build.gradle配置系列(一)]android studio根据版本号动态生成apk名
-
Android 动态加载二维码视图生成快照的示例
-
Android开发中button按钮的使用及动态添加组件方法示例
-
[build.gradle配置系列(一)]android studio根据版本号动态生成apk名
-
Android -- 打包release版本apk, 动态生成apk版本名, 打包.jar
-
Android中Zxing二维码的扫描、生成(带有动态权限申请)
-
android 多个edittext 判空监听 让Button动态是否可点击
-
Android动态生成Relativelayout + button
-
Android非XML形式动态生成、调用页面的方法
-
Android开发中button按钮的使用及动态添加组件方法示例