Android动态控制生成器

时间:2011-11-21 06:54:12

标签: android relativelayout

我正在寻找Android中的UI控件生成器。我有一个Web服务,它将提供创建表单类型的信息。该Web服务将告诉我该表单上需要的所有控件(可以是 TextView RadioButton CheckBox Spinner 等)和左/右位置wrt其他控件。

为此,我需要编写一个泛型类,它将返回我将从Web服务获得的该控件的对象。泛型类将有一个返回 RelativeLayout.LayoutParams 的函数,比如,alignToLeft(generic controlObject,int),其中第一个arg是该控件的对象,第二个arg是alignToLeft的引用控件的id /正确的位置。然后使用 addView addRule (参数)将该控件添加到 RelativeLayout

我的问题是我如何创建一个新的控件实例并将其传递给一个函数,添加参数规则并将其添加到视图中?

1 个答案:

答案 0 :(得分:0)

public class DynamicDesignMainActivity extends Activity {


LinearLayout main_layout;
jsonparser json_parser=null;
String jsonurl="URL STRING";
ProgressDialog progress_dialog;
JSONObject json_object_main;

private static final String TAG_NAME_MAIN="name";
private static final String TAG_JOBTYPE ="jobtype";
private static final String TAG_SECTION="sections";
private static final String TAG_SEC_1="sec-1";
private static final String TAG_NAME_MIDDEL="name";
private static final String TAG_OPTIONS="options";
private static final String TAG_NAME_INNER="name";
private static final String TAG_ID="id";
private static final String TAG_VALUES="values";
private static final String TAG_YES="yes";
private static final String TAG_NO="no";
private static final String TAG_TYPE="type";
private static final String TAG_ADDITIONAL_NOTE="additional_note";


class AsynctaskOperation extends AsyncTask<String, String, String>
{
    Context context;
    String json_string;
    public AsynctaskOperation(Context con) {
        // TODO Auto-generated constructor stub
        context=con;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        progress_dialog.show();
        json_parser=new jsonparser();
    }


    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        json_string=json_parser.getJsonfromUrl(jsonurl);
        return null;
    }


    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        progress_dialog.dismiss();
        Toast.makeText(DynamicDesignMainActivity.this, json_string,     Toast.LENGTH_LONG).show();
        try {

            json_object_main=new JSONObject(json_string);

            String name_main=json_object_main.getString(TAG_NAME_MAIN);
            String job_typew=json_object_main.getString(TAG_JOBTYPE);

            JSONObject  json_section=json_object_main.getJSONObject(TAG_SECTION);
            JSONObject  json_sec=json_section.getJSONObject(TAG_SEC_1);

            String mid_name=json_sec.getString(TAG_NAME_MIDDEL);


            main_layout=(LinearLayout)findViewById(R.id.main_LinearLayout);

            JSONArray json_option=json_sec.getJSONArray(TAG_OPTIONS);
            for(int i=0;i<json_option.length()-1;i++)
            {

                LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                LinearLayout linearlauout1=new LinearLayout(context);
                linearlauout1.setOrientation(LinearLayout.VERTICAL);
                linearlauout1.setLayoutParams(params);

                LinearLayout linearlayout_question=new LinearLayout(context);
                linearlayout_question.setLayoutParams(params);

                TextView textview_question=new TextView(context);
                textview_question.setLayoutParams(params);


                LinearLayout linearlayout_option=new LinearLayout(context);
                linearlayout_option.setOrientation(LinearLayout.VERTICAL);
                linearlayout_option.setLayoutParams(params);

                JSONObject jsonobject=json_option.getJSONObject(i);
                String question_name=jsonobject.getString(TAG_NAME_INNER);
                textview_question.setText(question_name);

                String type=null;
                type=jsonobject.getString(TAG_TYPE);
                Log.i("TYPE",type);
                JSONObject json_values=jsonobject.getJSONObject(TAG_VALUES);

                String val1=json_values.getString(TAG_YES);
                String val2=json_values.getString(TAG_NO);
                RadioGroup rg=null;
                String values[]={val1,val2};
                if(type.equalsIgnoreCase("radio"))
                {
                    RadioButton[] rb=new RadioButton[2];
                    rg=new RadioGroup(context);
                    rg.setOrientation(RadioGroup.HORIZONTAL);
                    for(int j=0;j<2;j++)
                    {
                        rb[j]=new RadioButton(context);
                        rb[j].setText(values[j]);
                        rg.addView(rb[j]);
                    }

                }

                main_layout.addView(linearlauout1);
                linearlauout1.addView(linearlayout_question);
                linearlauout1.addView(linearlayout_option);
                linearlayout_question.addView(textview_question);
                linearlayout_option.addView(rg);



            }

            Button btn_show=new Button(context);
            btn_show.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
            btn_show.setText("Show");
            btn_show.setId(101);
            btn_show.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    switch (v.getId()) {
                    case 101:

                        showAnswer(main_layout);
                        break;

                    default:
                        break;
                    }

                }
            });

            main_layout.addView(btn_show);




        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dynamic_design_main);

    progress_dialog=new ProgressDialog(this);
    progress_dialog.setMessage("Loading...");

    new AsynctaskOperation(this).execute();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.dynamic_design_main, menu);
    return true;
}

public void showAnswer(ViewGroup parent)
{
    //Log.i("Count",parent.getChildCount()+"");
    for(int j=0;j<parent.getChildCount();j++)
    {
        View child= parent.getChildAt(j);
        //Log.i("CALSS",child.getClass().toString());
        if(child instanceof TextView)
        {

            Log.i("TEXT",((TextView)child).getText()+"");
        }
        else
        {
            ViewGroup group=(ViewGroup)child;
            showAnswer(group);
        }
    }
}

}

public class jsonparser {

int code;
static InputStream is=null;
String json=null;
    public jsonparser() {
    // TODO Auto-generated constructor stub
    }

    public String getJsonfromUrl(String url)
    {
    StringBuilder builder=new StringBuilder();

    DefaultHttpClient httpClient=new DefaultHttpClient();

    HttpPost httppost=new HttpPost(url);

    try {

        HttpResponse httpResponse=httpClient.execute(httppost);

        code=httpResponse.getStatusLine().getStatusCode();

        if(code==200)
        {
            HttpEntity httpentity=httpResponse.getEntity();
            is=httpentity.getContent();

            BufferedReader br=new BufferedReader(new      InputStreamReader(is, "iso-8859-1"), 8);

            String line=null;
            while((line=br.readLine())!=null)
            {
                builder.append(line+"\n");
            }
            is.close();
        }
        json=builder.toString();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return json;

        }

    }