2016-06-22 126 views
0

我使用android studio開發應用程序,我想要一個包含取決於位置而變化的選項列表的表格,例如,如果我在紐約市我想顯示3個選項,但如果我在聖地亞哥,我想要5.我的想法是有一個線性佈局,它具有wrap_content作爲其中每個選項的其他線性佈局的高度。問題是我不知道如何修改(添加/刪除)內部佈局,或者是否有更好的方法來實現這個想法。用戶也可以選擇其中一個選項,它們是可點擊的。根據android studio中的位置動態調整線性佈局

下面是一些例子

enter image description here enter image description here

回答

1

這裏是我嘗試添加線性佈局動態的代碼,它工作:)。首先加載要在其中動態創建線性佈局的父佈局。然後,您必須決定要顯示的佈局數量,並將其傳遞給代碼中的'NumberOfLayouts'變量,以便動態創建線性佈局。

/*Loading the Parent Layout*/ 
LinearLayout ParentLayout = (LinearLayout)findViewById(R.id.ParentLayout); 

    /*Dynamically creating your linear layouts*/ 
    for(int i=0; i<NumberOfLayouts; i++){ 
     LinearLayout linearLayout = new LinearLayout(getApplication()); 

     TextView textView = new TextView(this); 
     textView.setText("Sample Text"); 

     linearLayout.addView(textView); 

     ParentLayout.addView(linearLayout); 

     /*Adding listener for the individual layouts*/ 
     linearLayout.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       //Your code or method to be executed while clicking the dynamically created linear layout 
      } 
     }); 
    } 
1
 // first, find the container view by using findViewById; 
    LinearLayout root = (LinearLayout) findViewById(R.id.container); 

    // then inflate the child view by using an inflater 
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View childView = inflater.inflate(R.layout.childView, null); 

    // finally, add the child view to the container 
    root.addView(childView); 
2

這可能是與RecyclerView更好地完成。它將允許您生成視圖列表並控制出現次數和設計。 RecyclerView可以滾動,因此它可以適應任何佈局。