Android:无法在布局中夸大EditText

时间:2014-07-10 08:53:38

标签: android

我正试图在EditText RelativeLayout内的Activity内展开RelativeLayout relLayout= new RelativeLayout(insideActivity); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); relLayout.setLayoutParams(params); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.holo_edit_text, null); EditText searchBox = (EditText)view.findViewById(R.id.holo_text); relLayout.addView(searchBox); 视图。

但是收到错误说:

  

指定的孩子已经有父母。您必须先在孩子的父母身上调用removeView()。

我的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText 
        android:id="@+id/holo_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true" />

</RelativeLayout>

这是holo_edit_text.xml

{{1}}

4 个答案:

答案 0 :(得分:0)

你的holo_edit_text.xml应该是

<?xml version="1.0" encoding="utf-8"?>
    <EditText 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/holo_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
     />

将视图添加到视图中的方式应该是这样的

编辑(改用getLayoutInflater())

 View view = getLayoutInflater().inflate(R.layout.holo_edit_text, null);
 //EditText searchBox = (EditText)view.findViewById(R.id.holo_text);
 //The last sentence is not neccesary
 relLayout.addView(view);

您是否在添加到相对布局时尝试了此操作

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
    relLayout.addView(view, params);

答案 1 :(得分:0)

试试这个..

View child_view = LayoutInflater.from(this).inflate(R.layout.holo_edit_text, null);
relLayout.addView(child_view);

答案 2 :(得分:0)

使用try / catch机制。

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (rootView != null) {
                ((ViewGroup) rootView.getParent()).removeView(rootView);
            }
              try {
               rootView = inflater.inflate(R.layout.your_layout_file_here, container,false);
               EditText searchBox = (EditText)rootView.findViewById(R.id.holo_text);
               relLayout.addView(searchBox);
              } catch (InflateException e) {

              }
            return rootView;
        }

答案 3 :(得分:0)

我已经修复了我的问题,只需将LayoutParams设置为searchBox,然后再将其添加到RelativeLayout。它的工作正常。

感谢大家的回复。