2016-10-14 5 views
0

Я пытаюсь добавить LinearLayout в качестве ребенка в другой компонент LinearLayout, но он вообще не появится на экране.LayoutInflater не работает для Android

XML:

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:orientation="horizontal" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/ReceivedMessage" 
android:background="@android:color/holo_blue_light" 
android:visibility="visible" 
tools:showIn="@layout/content_chat"> 

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:srcCompat="@mipmap/ic_launcher" 
    android:id="@+id/ProfilePicture" 
    android:layout_weight="1" /> 

<TextView 
    android:text=" Message" 
    android:layout_width="305dp" 
    android:layout_height="match_parent" 
    android:id="@+id/MessageText" 
    android:gravity="center_vertical" /> 
</LinearLayout> 

Код:

Button testMessageButton = (Button) findViewById(R.id.TestMessageButton); 
    testMessageButton.setOnClickListener(new View.OnClickListener() 
    { 
     public void onClick(View view) 
     { 
      LinearLayout msgLayout = (LinearLayout) findViewById(R.id.MessageLayout); 

      LayoutInflater vi = (LayoutInflater)getBaseContext() 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      View v = vi.inflate(R.layout.message_received, msgLayout, false); 


      msgLayout.addView(v); 
     } 
    }); 

Что вызывает компонент не появляется на экране?

+0

Вы просто хотите добавить линейную линейку в другую линейную линию? Так что же это инфлятор? Почему ты использовал это? –

+0

Поскольку родительский LinearLayout является вертикальным и используется только для сортировки. Горизонтальный LinearLayout, который я хочу вставить, содержит изображение и текст. Я использовал инфлятор, потому что вы не можете клонировать LinearLayout. – ashjack

ответ

0

Ваш вопрос не является правильным, но я отвечу двумя различными способами

Во-первых, если LinearLayout вы хотите добавить в другой файл XML, то вы можете надуть файл XML и добавить его в родительском LinearLayout в классе деятельности, как этот

Button testMessageButton = (Button) findViewById(R.id.TestMessageButton); 
testMessageButton.setOnClickListener(new View.OnClickListener(){ 
    public void onClick(View view){ 
     LinearLayout msgLayout = (LinearLayout) findViewById(R.id.MessageLayout); 

     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
     LayoutInflater vi = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View v = vi.inflate(R.layout.message_received, null); 
     v.setLayoutParams(params); 

     msgLayout.addView(v); 
    } 
}); 

Я обновил свое решение. Часть проблемы находится в файле макета

Это класс Activity

import android.content.Context; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.widget.Button; 
import android.widget.LinearLayout; 

public class MainActivity extends AppCompatActivity { 

private LinearLayout mainLayout; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mainLayout = (LinearLayout)findViewById(R.id.main_layout); 
    Button addChatButton = (Button)findViewById(R.id.add_chat); 
    addChatButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
      LayoutInflater vi = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      LinearLayout mView = (LinearLayout)vi.inflate(R.layout.test_layout, mainLayout, false); 
      mView.setLayoutParams(params); 
      mainLayout.addView(mView); 
     } 
    }); 
    } 
} 

Файл макета XML для класса активность

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/main_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.inducesmile.mylinear.MainActivity"> 

<Button 
    android:id="@+id/add_chat" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="80dp" 
    android:text="@string/add_chat" 
    android:layout_gravity="center|center_horizontal"/> 
</LinearLayout> 

Наконец, файл макета, который содержит LinearLayout быть завышена и добавлена ​​в корневой LinearLayout.

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:orientation="horizontal" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:id="@+id/ReceivedMessage" 
android:background="@android:color/holo_blue_light" 
android:visibility="visible"> 

<ImageView 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:src="@mipmap/ic_launcher" 
    android:id="@+id/ProfilePicture" 
    android:layout_weight="2" /> 

<TextView 
    android:text="@string/message" 
    android:layout_width="0dp" 
    android:layout_height="wrap_content" 
    android:id="@+id/MessageText" 
    android:layout_weight="7" 
    android:paddingTop="14dp" 
    android:paddingBottom="14dp" 
    android:gravity="center_vertical" /> 

</LinearLayout> 

enter image description here

+0

Благодарим вас за ответ. Мой случай - это первый случай, и я попытался использовать код, но компонент все еще не отображается в LinearLayout. – ashjack

+0

Добавить mlinearLayout.setOrientation (LinearLayout.HORIZONTAL); и есть ли у вас какие-либо ошибки в вашем логарифме? – Inducesmile

+0

Я добавил функцию и до сих пор не повезло. Logcat также не показывает никаких ошибок. – ashjack

0

на основе Inducesmile при добавлении Чайлдс в родительских контейнеров работает, то проблема может возникнуть, поскольку родительский контейнер не помещается внутри Scrollview, так что все Чайлдс вы добавляете не будут видны вам если вы хотите убедиться, что представление уже добавлено, просто вызовите parentlayout.getChildCount() после добавления любого ребенка