Pergunta

Eu tenho um layout definido no XML. Ele também contém:

<RelativeLayout
    android:id="@+id/item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
/>

Gostaria de inflar essa visão relativa com outro arquivo de layout XML. Posso usar layouts diferentes, dependendo de uma situação. Como devo fazer isso? Eu estava tentando diferentes variações de

RelativeLayout item = (RelativeLayout) findViewById(R.id.item);
item.inflate(...)

Mas nenhum deles funcionou bem.

Foi útil?

Solução

Não tenho certeza se tenho seguido sua pergunta- você está tentando anexar uma visão da criança à RelativeLayout? Se sim, você quer fazer algo parecido com:

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
item.addView(child);

Outras dicas

Você infla um recurso XML. Veja o LayoutInflater Doc .

Se o seu layout estiver em um mylayout.xml, você faria algo como:

View view; 
LayoutInflater inflater = (LayoutInflater)   getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);

RelativeLayout item = (RelativeLayout) view.findViewById(R.id.item);

Embora tardio, mas gostaria de acrescentar uma maneira de conseguir isso

LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = layoutInflater.inflate(R.layout.mylayout, item );

Onde item é o layout dos pais onde você deseja adicionar um layout filho.

É útil acrescentar a isso, mesmo que seja um post antigo, que, se a visualização da criança que está sendo inflada no XML deve ser adicionada a um layout do ViewGroup, você precisa chamar inflado com uma pista de que tipo de grupo de vista está indo a ser adicionado a. Curti:

View child = getLayoutInflater().inflate(R.layout.child, item, false);

O método inflado está bastante sobrecarregado e descreve essa parte do uso nos documentos. Eu tive um problema em que uma única visualização inflada do XML não estava alinhada no pai corretamente até que eu fiz esse tipo de alteração.

Uma maneira ainda mais simples é usar

View child = View.inflate(context, R.layout.child, null)
item.addChild(child) //attach to your item

inflação de layout

View view = null;
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
view = inflater.inflate(R.layout.mylayout, null);
main.addView(view);

Se você não está em uma atividade, pode usar a estática from() Método do LayoutInflater classe para conseguir um LayoutInflater, ou solicitar o serviço do método de contexto getSystemService() também :

LayoutInflater i;
Context x;       //Assuming here that x is a valid context, not null

i = (LayoutInflater) x.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//OR
i = LayoutInflater.from(x);

(Eu sei que é quase 4 anos atrás, mas ainda vale a pena mencionar)

Se você deseja adicionar uma única visualização várias vezes, então você deve usar

   layoutInflaterForButton = getActivity().getLayoutInflater();

 for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
        FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);
        btnContainer.addView(btnView);
    }

Se você gosta

   layoutInflaterForButton = getActivity().getLayoutInflater();
    FrameLayout btnView = (FrameLayout) layoutInflaterForButton.inflate(R.layout.poll_button, null);

e

for (int noOfButton = 0; noOfButton < 5; noOfButton++) {
            btnContainer.addView(btnView);
        }

Em seguida, ele lançará exceção de todas as visualizações adicionais prontas.

AnextToToot definido como true

Basta pensar que especificamos um botão em um arquivo de layout XML com sua largura de layout e altura do layout definida como MATCH_PARENT.

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/custom_button">
</Button>

Neste evento, clique em Evento, podemos definir o seguinte código para inflar o layout nesta atividade.

LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.yourlayoutname, this);

Espero que esta solução funcione para você.!

Tive mais dificuldade com esse erro, por causa das minhas circunstâncias únicas, mas finalmente encontrei uma solução.

Minha situação: estou usando uma visão separada (xml) que contém um WebView, então abre em um AlertDialog Quando clico em um botão na minha visão principal da atividade. Mas de alguma forma ou de outro WebView pertencia à visão principal da atividade (provavelmente porque eu puxo o recurso daqui), então logo antes de atribuí -lo ao meu AlertDialog (como vista), eu tive que fazer com que o pai do meu WebView, coloque -o em um ViewGroup, depois remova todas as vistas sobre isso ViewGroup. Isso funcionou e meu erro foi embora.

// set up Alert Dialog box
AlertDialog.Builder alert = new AlertDialog.Builder(this);
// inflate other xml where WebView is
LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(R.layout.your_webview_layout, null);
final WebView webView = (WebView) v.findViewById(R.id.your_webview_id);

// more code...

.... mais tarde depois que eu carreguei meu WebView ....

// first, remove the parent of WebView from it's old parent so can be assigned a new one.
ViewGroup vg = (ViewGroup) webView.getParent();
vg.removeAllViews();

// put WebView in Dialog box
alert.setView(webView);
alert.show();

Se você está tentando anexar uma visão da criança ao RelativeLayout? você pode fazer seguindo

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, item, true);

Experimente este código:

  1. Se você apenas deseja inflar seu layout:

View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,null); // Code for inflating xml layout
RelativeLayout item = view.findViewById(R.id.item);   

  1. Se você deseja inflar seu layout no contêiner (layout dos pais):

LinearLayout parent = findViewById(R.id.container);        //parent layout.
View view = LayoutInflater.from(context).inflate(R.layout.your_xml_layout,parent,false); 
RelativeLayout item = view.findViewById(R.id.item);       //initialize layout & By this you can also perform any event.
parent.addView(view);             //adding your inflated layout in parent layout.

Com Kotlin, você pode usar:

val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)

[your_main_layout].apply {
    //..
    addView(content)
}

Eu tinha usado abaixo do trecho de código para isso e funcionou para mim.

LinearLayout linearLayout = (LinearLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, null);
linearLayout.addView(child);

Não precisa de qualquer complexidade que seja simples como

 setContentView(R.layout.your_layout);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top