[英]How to set a text from my AsyncTask to a textview in a fragment?
[英]Set new TextView to fragment in AsyncTask
我想在Fragment中添加一個新的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
是兩個不同的類
這對我不起作用。 誰能告訴我為什么?
您不需要在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();
}
我發現你必須轉換解決方案View
中的Layout
要 ViewGroup
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 {
((ViewGroup)activity.findViewById(R.id.mylinearLayout)).addView(text);
} catch (Exception e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.