是否可以创建一种方法来扩展布局(或动态创建),向其添加特定视图(在本例中为 TextViews),然后将布局重新调整为视图,因此我可以(以某种方式)将其合并到主另一个类中的布局,如嵌套,但动态添加元素?
3 回答
是的,您可以使用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;
}
Yes, it is. I do a similar thing in my app. I'm writing a flashcard app, and I use a scrollview to show the user all the decks they have created. The code is commented:
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
Basically, you need to inflate the view from a new layout and then call findViewById() as a method of the new View you've created. From there, it's just like manipulating the current view the user can see. You can do anything you want from there.