【发布时间】:2017-02-13 15:16:30
【问题描述】:
我对 java 和 android studio 比较陌生,所以任何解释都将不胜感激。
我想创建一个应用程序,允许用户输入某人的姓名并将他们分配给两个团队之一。我现在用户可以为每个团队添加一个名称,但我不确定如何为每个团队添加多个名称。
在我的 XML 中,我有一个 EditText 字段来输入名称,两个按钮可以将它们放入 Team 1 或 Team 2 中,还有两个 TextViews 来显示每个团队中的所有人。
<EditText
android:layout_width="106dp"
android:layout_height="wrap_content"
android:id="@+id/NameText"/>
<Button
android:id="@+id/Team1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Team 1"/>
<Button
android:id="@+id/Team2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Team 2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/team1_person1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/team1_person2"
android:layout_column="1"/>
这是我的 java 代码,我已设置每个按钮以将输入的名称添加到团队 1 或团队 2 的 TextView,具体取决于选择的按钮。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button t1button = (Button) findViewById(R.id.Team1);
Button t2button = (Button) findViewById(R.id.Team2);
t1button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// --- find the text view --
EditText inputText = (EditText) findViewById(R.id.NameText);
String str = inputText.getText().toString();
TextView newText = (TextView) findViewById(R.id.team1_person1);
newText.setText( str);
}
});
t2button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// --- find the text view --
EditText inputText = (EditText) findViewById(R.id.NameText);
String str = inputText.getText().toString();
TextView newText = (TextView) findViewById(R.id.team1_person2);
newText.setText( str);
}
});
}
}
I know I'll need to add more TextViews for each new name, but I'm not sure how this works with only one button.
Thanks
【问题讨论】:
标签: java android xml button android-edittext