【问题标题】:Button (android.content.Context) in Button Cannot be Applied to (Java.lang.Object)按钮中的按钮(android.content.Context)无法应用于(Java.lang.Object)
【发布时间】:2018-09-29 19:47:17
【问题描述】:

我正在尝试动态创建按钮以匹配数据表。我使用这个answer 作为参考点但是我不断收到这个错误代码:Button (android.content.Context) in Button Cannot be Applied to (Java.lang.Object) 我尝试了多种方法来缓解错误代码,但我不知道如何修复它我试图将 Map 设置为数组,但这也不起作用。代码已成功计数并显示数据,但我无法让它添加所需的按钮。

 Backendless.Data.of( "Store" ).find( queryBuilder, new AsyncCallback<List<Map>>()
                {
                    @Override
                    public void handleResponse( List<Map> response )
                    {

                       int numBrands = response.size();

                       Button brandButtons[] = new Button[numBrands];

          System.out.println("The Count of Buttons:" + numBrands);

           ArrayList<Brands> productList  = new ArrayList<>();



             Object[] arrayList = {response};
            for(int i = 0; i < brandButtons.length; i++)
                        {

                        Button brans = new Button(productList[i]);

                            brans.setOnClickListener();
                            add(brans);
                            brandButtons[i] = brans;




                            //Object element = thisIsAStringArray[i];
                            System.out.println( "List of Brands" + response );




                        }

                    }

【问题讨论】:

    标签: java android arrays button


    【解决方案1】:

    你的错误在这一行:

    Button brans = new Button(productList[i]); // here
    

    Button 类期望 Context 传递给它的构造函数调用,而您正在传递 Object 类型。

    这样使用,

    Button brans = new Button(context); // here context can be activity or fragment.
    
    //now use this brans object to set property to your programmatically created Button, 
    //don't forget to add it to your parent view afterwards
    

    【讨论】:

    • 只是我的一个愚蠢的疏忽,谢谢
    • 哈哈,没问题,偶尔会发生。
    【解决方案2】:

    正如您在Button 文档中所见,要创建一个按钮对象,您需要传递一个Context 对象。在您的代码中,您传递了一个导致问题的 Brands 对象。

    解决方案是将上下文传递给Button(Context) 构造函数。如果你在一个 Activity 中,它会像新的Button(YourActivity.this),在一个片段中你可以使用new Button(getContext())

    【讨论】:

      猜你喜欢
      • 2019-04-09
      • 2014-12-12
      • 2018-05-24
      • 1970-01-01
      • 2020-10-01
      • 2016-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多