2017-05-25 77 views
1

嗨,我想在Android中動態創建按鈕,但是當我嘗試設置背景下這方面,我有一個問題: enter image description here新的按鈕背景問題,而動態地創建

這裏是代碼:

JSONArray jsonArr = new JSONArray(result); 
for (int i=0; i < jsonArr.length(); i++) { 
    JSONObject building = jsonArr.getJSONObject(i); 
    Log.i("results", building.optString("name")); 
    Button myButton = new Button(this); 
    myButton.setText("Push Me"); 

    LinearLayout ll = (LinearLayout)findViewById(R.id.buildingLL); 
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
    ll.addView(myButton, lp); 

}

有人可以幫助我嗎?

+1

是Activity類或者其他類是不活動? –

+1

可能'this'不是Activity的上下文。讓我們嘗試使用'MainActivity.this' 或顯示更多代碼 –

+0

這是私人類WebServiceHandler擴展AsyncTask { –

回答

1

提供從那裏WebServiceHandler被稱爲&上下文然後

Button myButton = new Button(mContext); // mContext is the context received on WebServiceHandler class 

如果WebServiceHandler是私有類的任何活動,然後

Button myButton = new Button(YOUR_ACTIVITY.this);