Button中的按钮(类)不能应用于类

时间:2019-08-05 08:29:29

标签: java android android-asynctask android-button android-context

我正在编写一个使用AsyncTask的Android应用程序。我在“ onPostExecute”无效中得到以下错误:

def names = "lucas,Fred,Mary"

for (i in names.split(',')) {
   println '"'+i+'"'
}

我已经尝试将“ this”语句更改为“ getContent()”和“ MainAtivity.this ”。 当我键入“ get Content()”时,它说:无法解析 当我输入“ MainActivity.this”时,它说:MainActivity不是一个封闭的类

public class NamesBinding extends Binding{
    @Delegate Binding delegate;
    public Object getVariable(String name) {
        //when variable declared - return the value, otherwise return the quoted name
        return delegate.hasVariable(name) ? delegate.getVariable(name) : "${groovy.json.JsonOutput.toJson(name)}"
    }
}

this.setBinding(new NamesBinding(delegate:this.getBinding()))

def names = [lucas,Fred,Mary]

for (i in names) {
   println i
}

此行中发生错误:

Button (android.content.Context) in Button cannot be applied to >(com.****.OnlineProductList)

1 个答案:

答案 0 :(得分:0)

您需要传递Context来创建Button,当前您正在传递OnlineProductListAsyncTask)对象。

您可以将Context实例作为构造函数参数传递(并保留一个WeakReference以避免内存泄漏)到OnlineProductList并使用该Context来创建您的Button

以下几行应该会起作用,


    public class OnlineProductList extends AsyncTask<Void,Void,Void>{
        private WeakReference<Context> contextRef;

        public OnlineProductList(Context context) {
            contextRef = new WeakReference<>(context);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);


            System.out.println("Program: " + productData.length / 3 + " Products found");

//create product objects



            Product[] product = new Product[productData.length / 3];
            for (int i = 0; i < product.length; i++) {

                product[i] = new Product(productData[3 * i], productData[1 + 3 * i], Boolean.parseBoolean(productData[2 + 3 * i]));

            }

            //create buttons for available products

            Context context = contextRef.get();
            if (context != null) {
                MainActivity.productButton = new Button[product.length];

                for (int i = 0; i < productData.length; i++) {

                    MainActivity.productButton[i] = new Button(this);
                    MainActivity.productButton[i].setWidth(MainActivity.orderHorizontalLayout.getWidth());
                    MainActivity.productButton[i].setHeight(MainActivity.orderHorizontalLayout.getHeight() / 10);
                    MainActivity.productButton[i].setText(product[i].name);

                    MainActivity.orderHorizontalLayout.addView(MainActivity.productButton[i]);
                }
            }
        }
    }