【发布时间】:2018-02-24 15:02:45
【问题描述】:
我目前正在尝试将用户定义数量的 TextViews 和 EditText 添加到活动中,但除了通过创建各种不同的活动对其进行硬编码之外似乎无法做到这一点。
此活动的目标是获取玩家的姓名,其数量由先前活动的额外意图中继。
我正在尝试添加一个 TextView 说“玩家 X:” 和一个 EditText 来输入每个玩家的玩家名称
我从这篇文章中知道:How to create a variable number of textviews in android 我必须以编程方式执行此操作,但是,它似乎对我不起作用(测试时活动保持空白)
我尝试创建一个临时 LinearLayout,我在 for() 中添加了两个视图,但仍然没有。
有什么想法吗?我在正确的轨道上吗?
最好的问候
[编辑] 代码在这里:
public class players extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_players);
Bundle extras = new Bundle();
final int numPlayers = extras.getInt("num");
final LinearLayout myLayout = findViewById(R.id.lin_Re);
final ArrayList<Player> players = new ArrayList<>();
int size = numPlayers; // total number of TextViews to add
TextView[] tv = new TextView[size];
TextView temp;
EditText[] et = new EditText[size];
EditText temp2;
LinearLayout temp3;
for (int i = 0; i < size; i++)
{
temp = new TextView(this);
temp2 = new EditText(this);
temp3 = new LinearLayout(this);
temp.setText("Player " + i + " : "); //arbitrary task
// add the textview to the linearlayout
temp3.addView(temp);
temp3.addView(temp2);
tv[i] = temp;
et[i] = temp2;
myLayout.addView(temp3);
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:id="@+id/lin_Re">
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/b_send"/>
</LinearLayout>
【问题讨论】:
-
发布您的代码可能是个好主意。
-
RecyclerView 确实是解决方案
-
刚刚编辑了问题!
标签: android android-edittext android-linearlayout textview