嗨,我想在 android 中创建动态按钮,但是当我尝试为此设置上下文时,我遇到了这个问题:
代码如下:
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);
有人可以帮我吗?
最佳答案
提供调用 WebServiceHandler 的上下文,然后
Button myButton = new Button(mContext); // mContext is the context received on WebServiceHandler class
如果WebServiceHandler是任何Activity的私有(private)类,那么
Button myButton = new Button(YOUR_ACTIVITY.this);
关于java - 动态创建时出现新按钮上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44189042/