How to change the dynamically displayed Layout

3

I want to do this, I currently have a ListView that is embedded within my activity_main.xml as follows:

<include layout="@layout/lista_categoria" />

I would like to know a way to display another layout (at runtime) within this include if the ListView is empty

for example showing layout layout_404.xml if you have nothing to display.

    
asked by anonymous 02.12.2016 / 18:17

4 answers

2

You can not change the content of a <include> , but you can do so in a ViewGroup. , because you can add and remove views from it.

At the place where you want to replace one view with another place a FrameLayout and give it an ID .

Create an xml for each of these views .

Create an object for each of them:

view1 = getLayoutInflater().inflate(R.layout.view1, null);
view2 = getLayoutInflater().inflate(R.layout.view2, null);

Get the reference to FrameLayout :

frameLayout = (FrameLayout) findViewById(R.id.frameLayout);

Add the first view to FrameLayout :

frameLayout.addView(layout1);

When you want to change view , remove views from FrameLayout and add the new

frameLayout.removeAllViews();
frameLayout.addView(layout2);

If you just want to put text when the list is empty, check out this answer .

    
02.12.2016 / 20:19
0

You have to define IDs for the layouts, type ex:

<LinearLayout ...
android:id="@+id/Layout1">

In the activity you want, you instantiate a layout, and assign it by ID:

LinearLayout layout1 = (LinearLayout) findById(R.id.Layout1);

LayoutInflater layoutInflater = (LayoutInflater) 
    this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
layout1.addView(1, layoutInflater.inflate(R.layout.content_layout, this, false) ); 

Note, attention to the layout type, (linear, relative .. etc)

    
02.12.2016 / 19:44
0
<include id="@+id/layout_1" layout="@layout/lista_categoria" android:visibility="visible" />
<include id="@+id/layout_2" layout="@layout/layout_404" android:visibility="gone" />

View layout1 = findViewById(R.id.lista_categoria);
View layout1 = findViewById(R.id.layout_404);

// Para fazer a troca
layout1.setVisibility(View.GONE);
layout2.setVisibility(View.VISIBLE);

// Para desfazer a troca
layout1.setVisibility(View.VISIBLE);
layout2.setVisibility(View.GONE);

It's not elegant anymore it works. The listView already has an implementation for empty layout. Look at this link: link

    
02.12.2016 / 19:46
0

Another way would be this.

 

 <TextView android:id="@+id/text1"
     android:textSize="16sp"
     android:textStyle="bold"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>

 <TextView android:id="@+id/text2"  //Esse layout aqui seria seu layout 404 customizado
     android:textSize="16sp"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"/>

    
02.12.2016 / 19:49