【问题标题】:how to Generate Dynamic Controll in android?如何在android中生成动态控制?
【发布时间】:2017-02-13 14:44:12
【问题描述】:

我想按用户特定值动态生成控件。 就像我有 ControlId、控件宽度、控件高度等的 EditText。 基于该值我想生成控制

LinearLayout L1 = new LinearLayout(this);
    L1.setOrientation(LinearLayout.VERTICAL);

    LinearLayout.LayoutParams L1paeam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    L1.setLayoutParams(L1paeam);

    TextView T1 = new TextView(this);
    T1.setText(R.string.Dynamic_text);
    L1.addView(T1);

    Button B1=new Button(this);
    B1.setText("Dynamic Button");
    L1.addView(B1);

    setContentView(L1);

在此代码中,指定了控件 ID Layout_height 和 Layout_width,但我希望它们作为用户指定

【问题讨论】:

    标签: android android-layout dynamic controls


    【解决方案1】:

    您可以在视图容器(LinearLayout、RelativeLayout 等)中添加任何视图,并在运行时删除这些视图。创建视图并为该视图指定布局参数。

    【讨论】:

      【解决方案2】:

      这是我找到的解决方案。

      public void generateButton(String Id,int Width,int Height,String text){
          @IdRes
                  int id = Integer.parseInt(Id);
          LinearLayout.LayoutParams L1param = new LinearLayout.LayoutParams(Width, Height);
          final Button B1=new Button(this);
          B1.setId(id);
          B1.setText(text);
          B1.setLayoutParams(L1param);
          B1.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                 // Button click operation goes here
              }
          });
          layout_main.addView(B1);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-17
        • 2013-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多