[英]LinearLayout nesting
是否有可能創建一種方法來對布局進行充氣(或動態創建),向其添加特定視圖(在這種情況下為TextViews),然后將布局重新調整為視圖,因此我可以(以某種方式)將其合並到主視圖中在另一個類中進行布局,例如嵌套,但是要動態添加元素?
是的,您可以使用LayoutInflater類來填充現有布局。 它會像這樣:
public static View GetLayout(final Context c){
final LayoutInflater inflater = LayoutInflater.from(c);
final View v = inflater.inflate(R.layout.activity_main, null);
//find the container where you want to insert your dynamic items
final LinearLayout placeholder = (LinearLayout) v.findViewById(R.id.linearLayout1);
//create the new textview
final TextView text = new TextView(c);
text.setText("Some text");
placeholder.addView(text, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
return v;
}
該問題要求將此視圖返回到“其他類”,而其他答案也在同一個類中執行-這意味着它具有上下文。 為了從另一個類中執行此操作,您需要像我在此處那樣傳遞上下文,或以其他方式傳遞(如果需要實例對象,則調用構造函數,等等)。
對的,這是可能的:
... onCreate()
{
setContentView(...);
ViewGroup myContainer=(ViewGroup)findViewById(R.id.myContainer);
View v=inflateMySpecialView();
//=<set layoutParams for the view if needed
myContainer.addView(v);
}
public View inflateMySpecialView()
{
ViewGroup viewgroup=(ViewGroup ) getLayoutInflater().inflate(R.layout.my_custom_layout, null,false);
//do some stuff with the inflated viewgroup.
return viewgroup;
}
是的。 我在我的應用程序中做了類似的事情。 我正在編寫一個抽認卡應用程序,並使用滾動視圖向用戶顯示他們創建的所有卡片組。 該代碼被注釋:
public void FillDeckView(){
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Deck testDeck = Deck.GetDeckFromDB();//Make a deck object from SQLite DB values
final int DECK_SIZE = 20;//Fill the view with this many decks
TableLayout scrollTable = (TableLayout) findViewById(R.id.scrollTable);
//This tableRow is in my main view
TableRow newTableRow = (TableRow) findViewById(R.id.tableRow4);
//This view I'm inflating is a separate android layout XML file
//I created, which shows the icon for the deck the user has made.
View deckViewBox = inflater.inflate(R.layout.deck_icons, null);
//Look, I'm getting a textview that's IN the deckViewBox, which is
//a separate View. Below, I'll change its text dynamically
TextView deckNameTV = (TextView) deckViewBox.findViewById(R.id.deckNameView);
int viewIndex = 1;
for(int i = 0; i < DECK_SIZE && testDeck != null; i++){
//First I'll change the text of the view, and then I'll add it in
deckNameTV.setText(testDeck.getName());
newTableRow.addView(deckViewBox);
if(i % 2 != 0){
//If we're on an odd number, make a new tableRow
newTableRow = new TableRow(getApplicationContext());
scrollTable.addView(newTableRow, viewIndex);
++viewIndex;
}
}
}//FillDeckView
基本上,您需要從新布局擴展視圖,然后調用findViewById()作為創建的新View的方法。 從那里開始,就像操縱用戶可以看到的當前視圖一樣。 您可以從那里做任何您想做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.