为了将项目动态添加到 ScrollView 中,我已经尝试了几个小时,试图按照各种教程进行操作,但似乎没有任何效果......
我的想法只是将字符串添加到复选框旁边的 TextView 中,这是在一个单独的 xml 文件中完成的,我只是希望列表随着我不断添加它们而增长。
目前,只添加了一个字符串(最后一个字符串替换了前一个字符串),并且在任何试图改变它的尝试中,我的应用程序都会停止工作。 这是目前的代码:
TableLayout addPlayersTableLayout;
TableRow tableRow1;
ScrollView addPlayersScrollView;
String[] players = new String[]{ "Blah", "Whatever", "Test", "Nipah!"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPlayersTableLayout = (TableLayout)findViewById(R.id.TableLayout1);
tableRow1 =(TableRow)findViewById(R.id.tableRow1);
addPlayersScrollView = (ScrollView)findViewById(R.id.playersScrollView);
insertPlayerInScrollView();
}
这是应该添加项目的函数的实现: (add_player_row.xml 是创建应该是项目的 TextView 和复选框的文件)
private void insertPlayerInScrollView() {
LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View newPlayerRow = inflator.inflate(R.layout.add_player_row, null);
TextView newPlayerTextView = (TextView) newPlayerRow.findViewById(R.id.addPlayerTextView);
CheckBox playerCheckBox = (CheckBox)findViewById(R.id.playerCheckBox);
newPlayerTextView.setText(players[1]);
addPlayersTableLayout.addView(newPlayerRow,0);
}
最后一行代码是它工作的唯一方式,即使在大多数论坛和教程中,人们会指示我使用 addPlayersScrollView,但如果我这样做,应用程序就会崩溃。 所以...有什么想法吗? 非常感谢!
最佳答案
我遇到了和你类似的事情。我有这样的布局:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:id="@+id/tableLayoutList"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
然后像这样定义我的行 (mRowLayout.xml):
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayoutRow"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/checkBoxServEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
然后我使用以下代码来膨胀我的行:
private void fillTable(View v, Cursor c) {
TableLayout ll = (TableLayout) v.findViewById(R.id.tableLayoutList);
View mTableRow = null;
int i = 0;
while(!c.isAfterLast()){
i++;
mTableRow = (TableRow) View.inflate(getActivity(), R.layout.mRowLayout, null);
CheckBox cb = (CheckBox)mTableRow.findViewById(R.id.checkBoxServEmail);
cb.setText( c.getString(c.getColumnIndex(Empleado.EMAIL)));
mTableRow.setTag(i);
//add TableRows to TableLayout
ll.addView(mTableRow);
c.moveToNext();
}
}
我在这里尝试做的是动态地增加我的行。光标有我想从数据库中显示的项目。我不确定这是否可以解决您的问题。让我知道。
关于java - Android-动态添加项目到 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17242493/