[英]Change child LinearLayout visibility “onClick” ing a TextView inside parent LinearLayout
[英]Find child of a LinearLayout inside a LinearLayout
我有一个已经在xml中创建的LinearLayout(“ ll”),应用程序在其中动态创建了另一个LinearLayout,并在该视图内部创建了一个EditText和一个Button。 该按钮使整个LinearLayout及其内部的EditText和Button自行销毁(整个系统是一个输入活动的玩家名称)。 无论如何,我试图找到一种方法来从所有EditText中获取文本。 我曾尝试在“ ll”上使用for循环并使用ll.getChildAt()
但由于ll.getChildAt()
生成的内容似乎无法使用.getChildAt()
,因为getChildAt()
生成“视图”而不是“ LinearLayout中“。 我基本上只需要一种方法来搜索两个孩子,而不是一个。 另外,如果有更好的方法应该执行此操作,请告诉我。 我愿意提出建议。
这是我的代码,如果有帮助的话:
NewGameCreate.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);
}
}
}
我想我找到了答案。 您需要在startGame()方法中更改一些代码,我在下面提供了startGame的代码。
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 = (LinearLayout) ll.getChildAt(loop);
for (int j = 0; j < inner.getChildCount(); j++) {
if (inner.getChildAt(j) instanceof EditText) {
EditText textET = (EditText) inner.getChildAt(j);
Log.d("TAG",textET.getText().toString());
}
}
}
}
在上面的代码中,您只能获得第一个孩子,但是由于您在方向为Vertical的父级LinearLayout中添加了一个Horizontal方向的linearLayout,因此您为父级布局的子级(即playerView)编写了代码。 我已经修改了代码以获取子线性布局的元素,并且Log从EditText打印所有文本。
希望有帮助!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.