安卓:添加布局动态地充气XML [英] Android: Adding Layouts Dynamically By Inflating XML

查看:161
本文介绍了安卓:添加布局动态地充气XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这里有一个布局将被添加到当按钮为pressed我的看法功能。 2 的EditText ■在布局的ID被添加到列表<的EditText> ,这样我就可以访问它们不在XML布局的许多情况都不管如何说。不过,我有麻烦得到这个工作。

I'm trying to have a function where a layout is added to my view when a button is pressed. The ID's of 2 EditTexts in the layout are added to a List<EditText>, so I can access them no matter how many instances of the XML layout are added. However, I'm having troubles getting this to work.

主要功能建立视图:

    ViewGroup view = null;
    TextView addressView;
    Button submit;
    ImageView addHeader;

    private int id = 0;
    private List<EditText> editTexts = new ArrayList<EditText>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get);

        view = (ViewGroup) findViewById(R.id.getLayout);


        addressView = (TextView) view.findViewById(R.id.getAddress);
        submit = (Button) view.findViewById(R.id.getSubmit);
        addHeader = (ImageView) view.findViewById(R.id.getHeaderAdd);

        addHeader.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addHeaderBox();
            }           
        });

我添加的功能布局:

My function adding the layout:

private void addHeaderBox() {    
    LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    inflater.inflate(R.layout.get_param, view, false);

    EditText nameBox = (EditText) view.findViewById(R.id.getValue);
    EditText valueBox = (EditText) view.findViewById(R.id.getName);

    nameBox.setId(id++);
    valueBox.setId(id++);

    editTexts.add(nameBox);
    editTexts.add(valueBox);
}   

的getValue 的getName 是两个的EditText 在我的布局(不是主要的 getLayout )。

getValue and getName are the ID's of the two EditTexts in my layout (not the main getLayout).

07-19 10:25:13.088: E/AndroidRuntime(32034): java.lang.NullPointerException
07-19 10:25:13.088: E/AndroidRuntime(32034):    at myapp.httprequest.free.GETActivity.addHeaderBox(GETActivity.java:96)
07-19 10:25:13.088: E/AndroidRuntime(32034):    at myapp.httprequest.free.GETActivity.access$0(GETActivity.java:88)
07-19 10:25:13.088: E/AndroidRuntime(32034):    at myapp.httprequest.free.GETActivity$1.onClick(GETActivity.java:65)

96号线 nameBox.setId(ID ++)

推荐答案

尝试:

.......
View someView = inflater.inflate(R.layout.get_param, view, false);

EditText nameBox = (EditText) someView.findViewById(R.id.getValue);
EditText valueBox = (EditText) someView.findViewById(R.id.getName);
........ 

这篇关于安卓:添加布局动态地充气XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆