【问题标题】:Automatic button creation when activity gets passed a string and icon活动通过字符串和图标时自动创建按钮
【发布时间】:2016-05-03 04:17:40
【问题描述】:

我想知道如何在我的活动通过字符串和图标时自动创建一个按钮。我有一个正在侦听端口以从计算机接收字符串和图像的活动。一旦这个图像和字符串被传递给我的应用程序,我希望我的应用程序自动创建一个按钮,使用该图像作为背景,字符串作为图像下的标签。

我想知道是否有人可以指点我如何开始,因为我什至不确定如何开始,并且在网上寻找解决方案时遇到了问题。

我还想知道如何将该新按钮放置在我的 GUI 上的特定位置。我希望新按钮出现在我的 GUI 中已有的另一个按钮下

public void createButton (Bitmap bitmap, String applicationName, LayoutInflater inflater, ViewGroup container){

    View rootView = inflater.inflate(R.layout.home_fragment, container, false);

    RelativeLayout rLayout = (RelativeLayout) rootView.findViewById(R.id.home_fragment);


    Button btn = new Button(getActivity());
    btn.setText(applicationName);

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.RIGHT_OF, app_row3_button3);
    btn.setLayoutParams(params);

    rLayout.addView(btn);




}

到目前为止,这是我的代码...这是扩展片段(不是活动)的类内部的一个方法。我收到“app_row3_button3”错误,这是我希望将新按钮放在旁边的按钮的 ID。这个现有的按钮已经在这个类中定义过。我的错误是:

wrong 2nd argument type. found: 'android.widget.ImageButton', required: 'int'

【问题讨论】:

    标签: java android button automation


    【解决方案1】:

    添加这些线,位置取决于LinearLayout位置,确保按钮在这个Linearlayout lin中

    ViewGroup linearLayout = (ViewGroup) findViewById(R.id.lin);//lin is your linear layout id
            bt.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            linearLayout.addView(bt);
    

    【讨论】:

      【解决方案2】:

      像这样动态创建一个按钮 -

          Button btn = new Button(this);
          btn.setText("your_text_here");
      
         RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                  RelativeLayout.LayoutParams.WRAP_CONTENT,
                  RelativeLayout.LayoutParams.WRAP_CONTENT);    
          params.addRule(RelativeLayout.BELOW, <first_button_id_here>);
          btn.setLayoutParams(params);
      

      然后将该按钮添加到您的RelativeLayout -

      rLayout.addView(btn);
      

      【讨论】:

      • 感谢您的帮助!我现在正在创建我的按钮,对于 ,它必须是一个 int 类型,所以这是我为我的按钮创建 ID 的地方,比如按钮 #1,将“1”插入到 params.addRule ?然后我为我的按钮分配“1”的ID?而且,“rLayout”应该是我想要添加按钮的布局的 ID?这对我不起作用,也许是因为我在扩展片段而不是活动的类中创建此按钮。
      • params.addRule(RelativeLayout.BELOW, &lt;first_button_id_here&gt;); 用于将新创建的按钮放在现有按钮下方。您需要将现有的按钮 ID 替换为 &lt;first_button_id_here&gt;
      • 我想出了 rLayout 的事情。但是对于 params.addRule,我得到了我需要将整数传递到“first_button_id_here”的错误。我无法传入我希望在其下创建新按钮的按钮小部件的 ID。
      • 您没有现有按钮的 ID?这也是动态的吗?
      • 我有一个现有按钮的 ID,但我不能将其设为整数,它告诉我整数是按钮的无效 ID,并且它必须以字符开头。但我只能将一个整数传递给 param.addRules
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      相关资源
      最近更新 更多