我正在尝试动态创建按钮以匹配数据表。我使用此答案作为参考点,但是我不断收到此错误代码: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 );
}
}
您的错误在此行中:
Button brans = new Button(productList[i]); // here
Button
类期望Context
传递给它的构造函数调用,而你传递的是对象类型。
像这样使用,
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
正如您在按钮文档中看到的,要创建按钮对象,您需要传递一个Context
对象。在您的代码中,您传递了一个导致问题的Brands
对象。
解决方案是将上下文传递给Button(Context)
构造函数。如果您在活动中,它将类似于新Button(YourActivity.this)
,在片段中您可以使用new Button(getContext())