Android动态控件生成器

发布于 2024-12-16 21:48:12 字数 555 浏览 0 评论 0原文

我正在寻找 android 中的 UI 控件生成器。我有一个网络服务,它将提供信息来创建表单之类的东西。该网络服务将告诉我该表单上需要哪些控件(可以是 TextViewRadioButtonCheckBoxSpinner 等)以及其他控件的左/右位置。

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

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

I am looking for a UI control generator in android. I have a web service which will provide information to create a form kind of thing. That web service will tell me what all controls I need on that form, (it can be TextView, RadioButton, CheckBox, Spinner etc) and left/right position w.r.t. other controls.

For this, I need to write a generic class that will return me the object of that control which i'll get from web service. The generic class will have a function that will return RelativeLayout.LayoutParams, say, alignToLeft(generic controlObject, int), where first arg is object of that control and second arg is id of the referenced control for alignToLeft/Right position. Then add that control to my RelativeLayout using addView and addRule (param).

My problem is how do i create a new instance of controls and pass it on to a function, add param rules and add it to view?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凶凌 2024-12-23 21:48:12
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);
        }
    }
}

}

公共类 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;

        }

    }
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;

        }

    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文