2014-11-25 2 views
15

Если я, например, иметь пустой макет так:Добавить несколько представлений пользовательских макет программно

layout1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

</LinearLayout> 

И некоторые другие Компоновка, как это:

layout2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="horizontal" > 

    <TextView 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="TextView 1" /> 

    <Button 
     android:id="@+id/button2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button 2" /> 

    <Button 
     android:id="@+id/button3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Button 3" 
     android:layout_weight="1"/> 

</LinearLayout> 

Я хотел бы добавить layout2.xml в layout1.xml p rogrammatically. Мне нужно было бы иметь несколько разных версий layout2.xml, которые я бы добавил, когда захочу. Каждый из них имел бы другой текст в TextView и Buttons.

В случае регулярного Android View я обычно делаю это так же, как это с addView:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    TextView tv1 = new TextView(this); 
    tv1.setText("HELLO"); 
    my_linear_layout.addView(tv1); 

    Button btn2 = new Button(this); 
    bt2.setText("WORLD"); 
    my_linear_layout.addView(btn2); 
} 

Как я могу это сделать, если я не имею что-то простое, как TextView или кнопки, и если у меня есть мой собственный xml определенный вид?

Возможно ли каким-либо образом разместить все виды внутри адаптера, как для ListView, а затем получить его при необходимости и просто вызвать addView на эти виды?

+0

Использование LayoutInflator сделать это См http://stackoverflow.com/questions/2335813/how-to-inflate -one-view-with-a-layout – user3917131

ответ

32

Вы можете надуть файл layout2.xml, редактировать тексты, и добавить его к первой схеме:

public class MyActivity extends Activity { 

    private ViewGroup mLinearLayout; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.layout1); 
     mLinearLayout = (ViewGroup) findViewById(R.id.linear_layout); 
     addLayout("This is text 1", "This is first button", "This is second Button"); 
    } 

    private void addLayout(String textViewText, String buttonText1, String buttonText2) { 
     View layout2 = LayoutInflater.from(this).inflate(R.layout.layout2, mLinearLayout, false); 

     TextView textView = (TextView) layout2.findViewById(R.id.button1); 
     Button button1 = (Button) layout2.findViewById(R.id.button2); 
     Button button2 = (Button) layout2.findViewById(R.id.button3); 

     textView1.setText(textViewText); 
     button1.setText(buttonText1); 
     button2.setText(buttonText2); 

     mLinearLayout.addView(layout2); 
    } 
} 

Вы можете изменить android:layout_height в целях layout2.xml корня к wrap_content.

7

Layout1 содержит Scrollview в качестве родительского макета и главного LinearLayout как ребенок, если не элемента строки больше размера экрана ScrollView ручки Переполнение элемент с пролистайте:

layout1.xml

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <LinearLayout 
     android:id="@+id/my_linear_layout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical"> 

    </LinearLayout> 
</ScrollView> 

Использования LayoutInflater добавить строку в материнской компании LinearLayout:

private LinearLayout my_linear_layout; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.layout1); 
    my_linear_layout = (LinearLayout) findViewById(R.id.my_linear_layout); 

    for(int i=1;i<=5;i++){ 
     View view = LayoutInflater.from(this).inflate(R.layout.layout2,null); 
     TextView button1 = (TextView) view.findViewById(R.id.button1); 
     Button button2 = (Button) view.findViewById(R.id.button2); 
     TextView button3 = (TextView) view.findViewById(R.id.button3); 

     button1.setText("HELLO " + i); 
     button2.setText("HELLO "+i); 
     button3.setText("HELLO "+i); 
     my_linear_layout.addView(view); 
    } 
} 
+0

Как получить доступ ко всей кнопке за пределами представления? –

+0

Попробуйте получить дочерний элемент из my_linear_layout или добавьте все кнопки, ссылки на один список массивов. –

+0

Указанный ребенок уже имеет родителя, пожалуйста, позвоните removeView() –

2

попробуйте этот метод

добавить идентификатор в LinearLayout layout1.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/firstlayout" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" > 

    </LinearLayout> 

В OnCreate

LinearLayout firstlayout=(LinearLayout)findviewbyId(R.id.firstlayout); 

    LinearLayout secondlayoout=(LinearLayout)this.getLayoutInflater().inflate(R.layout.layout2,null); //inflating view from xml 
    TextView btn1=(TextView)secondlayoout.findviewbyId(R.id.button1); 
    btn1.settext("TEST"); 

firstlayout.addview(secondlayoout); 
Смежные вопросы