2017-05-25 59 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);