我有一个已在 xml 中创建的 LinearLayout(“ll”),应用程序在其中动态创建另一个 LinearLayout,并在该视图内创建一个 EditText 和一个 Button。该按钮使整个LinearLayout连同其中的EditText和Button一起销毁(整个系统是一个玩家姓名输入活动)。无论如何,我正在尝试找到一种从所有 EditText 中获取文本的方法。我尝试在“ll”上使用 for 循环并使用ll.getChildAt()
,但我似乎无法在生成的.getChildAt()
任何内容上使用,ll.getChildAt()
因为getChildAt()
生成的是“View”而不是“LinearLayout”。我基本上只需要一种方法来搜索两个孩子,而不仅仅是一个。另外,如果有更好的方法我应该这样做,请告诉我。我愿意接受建议。
如果有帮助,这是我的代码:
新游戏创建.java
public class NewGameCreate extends Activity {
int numOfPlayers = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_game_create);
}
public void newPlayer(View view) {
numOfPlayers++;
final LinearLayout ll = findViewById(R.id.playerView);
final LinearLayout llNew = new LinearLayout(getApplicationContext());
llNew.setOrientation(LinearLayout.HORIZONTAL);
llNew.setId(numOfPlayers);
ll.addView(llNew);
EditText newName = new EditText(this);
newName.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
newName.setHint("Enter Player Name");
newName.setId(numOfPlayers);
newName.setWidth(0);
llNew.addView(newName);
final Button delete = new Button(this);
delete.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0));
delete.setText("Delete");
delete.setId(numOfPlayers);
delete.setWidth(0);
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int id = delete.getId();
ll.removeViewInLayout(findViewById(id));
Drawable back = ll.getBackground();
ll.setBackgroundColor(00000000);
ll.setBackground(back);
ll.invalidate();
}
});
llNew.addView(delete);
}
public void startGame(View view){
LinearLayout ll = findViewById(R.id.playerView);
List text = new ArrayList();
for(int loop = 0; loop < ll.getChildCount(); loop++) {
//this is the code in question and where I want to get the text from
//all my EditTexts
LinearLayout inner = ll.getChildAt(loop);
}
}
}