我想在片段中添加一个新的TextView
。这是我在asynctask backgroundjob类中的代码:
protected void onPostExecute(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("true")) {
/**********************************/
LayoutInflater inflater = activity.getLayoutInflater();
View mContainer = inflater.inflate(R.layout.fragment_home, null);
LinearLayout linearLayout = (LinearLayout)mContainer.findViewById(R.id.mylinearLayout);
TextView text = new TextView(linearLayout.getContext());
text.setText("TEST");
text.setTextSize(30);
Log.d("View", "Start");
try {
linearLayout.addView(text);
} catch (Exception e) {
e.printStackTrace();
}
这是我的片段类:
public class Home extends Fragment {
public Home() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TopicBackgroundTask backgroundTask = new TopicBackgroundTask(getActivity());
backgroundTask.execute("yes");
// Inflate the layout for this
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
注意:Home
片段和TopicBackgroundTask
是两个不同的类
这对我不起作用。谁能告诉我为什么?
答案 0 :(得分:0)
您无需再次在onPostExecute()
您需要重新使用onCreateView()
中给出的布局,
所以你必须创建一个全局变量视图,
将其设置在onCreateView()
而不是直接返回。
myView = inflater.inflate(R.layout.fragment_home, container, false);
和onPostExecute()
,
LinearLayout linearLayout = (LinearLayout)mContainer.findViewById(R.id.mylinearLayout);
TextView text = new TextView(linearLayout.getContext());
text.setText("TEST");
text.setTextSize(30);
Log.d("View", "Start");
try {
linearLayout.addView(text);
} catch (Exception e) {
e.printStackTrace();
}
答案 1 :(得分:0)
我找到了您必须投放!
至 View
Layout
的解决方案
ViewGroup