有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

当活动传递字符串和图标时,java自动创建按钮

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

我想知道是否有人能告诉我如何开始,因为我甚至不知道如何开始,并且在网上寻找解决方案时遇到了问题

我还想知道如何在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: '安卓.widget.ImageButton', required: 'int'

共 (2) 个答案

  1. # 1 楼答案

    动态创建一个按钮,如下所示-

        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);
    
  2. # 2 楼答案

    添加这些线,位置取决于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);