【问题标题】:Add a button dynamically in AsyncTask onPostExecute在 AsyncTask onPostExecute 中动态添加按钮
【发布时间】:2012-07-15 14:46:22
【问题描述】:

我正在尝试在AsyncTaskonPostExecute 方法中动态添加Button。我在扩展Fragment 的类中执行此操作。我可以使用此代码在AsyncTask 之外动态创建Button

public class Tab2Fragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) 
    {
        LinearLayout theLayout =  (LinearLayout) inflater.inflate(R.layout.tab2, container, false);
        Context mFragmentContext=getActivity().getApplicationContext(); 
        Button btn=new Button(mFragmentContext);
        btn.setText("Hello Button");
        RelativeLayout.LayoutParams paramsd = new RelativeLayout.LayoutParams(150,30);
        paramsd.height = paramsd.WRAP_CONTENT;
        paramsd.width = paramsd.WRAP_CONTENT;
        btn.setLayoutParams(paramsd);
        theLayout.addView(btn); 

        Button test = (Button)theLayout.findViewById(R.id.test41);
        test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v("response", "Button Clicked");
                new loadSomeStuff().execute();
                Intent log = new Intent();
                log.setClass(getActivity(), Assignment.class);
                startActivity(log);
            }
        });

        return theLayout;
    }

    // Method to load stuff using async task. Grabs information from URL and
    // calls read stream
    public class loadSomeStuff extends AsyncTask<String, Integer, String> {
        protected String doInBackground(String... arg0) {
            try {
                int limit = 100;
                String accessToken = "";
                URL url = new URL( "SomeSite" + accessToken 
                            + "&status=active" + "&limit=" + limit);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestProperty("Accept", "application/json");
                readStream(con.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute( String result )  {
            super.onPostExecute(result);

            Context mFragmentContext=getActivity().getApplicationContext(); 
            Button btn=new Button(mFragmentContext);
            btn.setText("Hello Button");
            RelativeLayout.LayoutParams paramsd = new RelativeLayout.LayoutParams(150,30);
            paramsd.height = paramsd.WRAP_CONTENT;
            paramsd.width = paramsd.WRAP_CONTENT;
            btn.setLayoutParams(paramsd);
            //theLayout.addView(btn); 

            Log.v("response", "on post biatch");
        }
    }

    // Processes information from URL and prints it in format
    private void readStream(InputStream in) throws JSONException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(in));

            String line = reader.readLine();
            String total_results = new JSONObject(line).getJSONObject(
                "response").getString("total_results");
            int assignCount = Integer.parseInt(total_results.toString());
            Log.v("response", total_results);
            JSONObject data;

            for (int i = 0; i < assignCount; i++) {
                data = new JSONObject(line).getJSONObject("response");
                String id = data.getJSONArray("data").getJSONObject(i).getString("id");
                String title = data.getJSONArray("data").getJSONObject(i).getString("title");
                Log.v("response", title);

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

问题是,当我尝试将此代码放入 AsyncTaskonPostExecute 时,addview(btn) 行出现错误,因为未定义 Layout。我不知道如何通过Layout。有没有办法通过某种内置方法来获取活动的Layout

【问题讨论】:

  • 如果您的Async Task 在同一班级,您可以将其公开。在其他情况下,您可以将Layout 作为Async Task 的构造函数传递给
  • 请发布您的所有代码。
  • 好的,添加了我所有的代码,我不能公开布局,它不会让我出于某种原因。说我只能做最后。这没有任何作用
  • 既然是内部类,就使用Fragment'sgetView()方法。它返回在 onCreate() 中返回的相同视图

标签: java android android-asynctask android-button dynamically-generated


【解决方案1】:

这对我来说可以以编程方式添加一个 RelativeLayout 并在其中放置一个按钮:

RelativeLayout.LayoutParams yourlayout = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);

yourlayout.addRule(RelativeLayout.ALIGN_PARENT_TOP,anotherview.getId());
yourlayout.addView(yourbutton, yourlayout);

如果您使用动态布局而不是静态 XML,我强烈建议您必须使用 setId() 并为每个视图分配一个唯一的 ID。这是使用其他视图引用定位视图所必需的。

【讨论】:

    【解决方案2】:

    您可以使用Handler; add the following to the mainActivity`:

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
            case 0:
                Context mFragmentContext=getActivity().getApplicationContext(); 
                Button btn=new Button(mFragmentContext);
                btn.setText("Hello Button");
                RelativeLayout.LayoutParams paramsd = new RelativeLayout.LayoutParams(150,30);
                paramsd.height = paramsd.WRAP_CONTENT;
                paramsd.width = paramsd.WRAP_CONTENT;
                btn.setLayoutParams(paramsd);
                // addView(btn) in your LinearLayout
                break;  
            }
        }
    };
    

    HandlerAsyncTask 构造函数一起传递,并在onPostExecute(String result) 中使用Handler,如下所示:

    public void onPostExecute(String result) {
        Message msg = new Message();
        msg.what = 0;
        handler.sendMessage(msg);
    }
    

    您可以在Handler 类中创建不同的事件,并使用msg.what 选择类型。

    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      为什么不向loadSomeStuff 类添加构造函数?在构造函数上,传递您要添加 ButtonView

      public class loadSomeStuff extends AsyncTask<String, Integer, String> {
          private View view;
      
          public loadSomeStuff(View v) {
              view = v;
          }
      
          public String doInBackground(String... strings) {
             //...
          }
      
          public void onPostExecute(String result) {
              //...
              view.addView(btn);
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-05-24
        • 1970-01-01
        • 1970-01-01
        • 2018-03-30
        • 1970-01-01
        • 2013-10-27
        • 2011-07-27
        • 2014-10-25
        • 1970-01-01
        相关资源
        最近更新 更多