问题
I have a LinearLayout inside a FrameLayout for tab purposes. And I'm trying to add TableRow's to the LinearLayout in the code.
LinearLayout testLayout = (LinearLayout)findViewById(R.id.testLayout);
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
This gets my LinearLayout and creates a TableRow to the specifications I want. I know this part is working.
TextView textOne = new TextView(this);
textOne.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
textOne.setText("One");
TextView textTwo = new TextView(this);
textTwo.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
textTwo.setText("Two");
Here I make my two TextViews with no problem.
tableRow.addView(textOne);
tableRow.addView(textTwo);
testLayout.addView(tableRow, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
Here is where I assume everything goes wrong. What happens is it only shows the textTwo. I don't know why it's not showing both of them in order like a normal TableRow would in XML. And I repeat, this must be done in code. Please help, thank you.
回答1:
Have you imported this import android.widget.TableRow.LayoutParams
Below code works for me
TableLayout tl = (TableLayout) findViewById(R.id.spreadsheet);
TableRow tr = new TableRow(this);
LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(lp);
TextView tvLeft = new TextView(this);
tvLeft.setLayoutParams(lp);
tvLeft.setBackgroundColor(Color.WHITE);
tvLeft.setText("OMG");
TextView tvCenter = new TextView(this);
tvCenter.setLayoutParams(lp);
tvCenter.setBackgroundColor(Color.WHITE);
tvCenter.setText("It");
TextView tvRight = new TextView(this);
tvRight.setLayoutParams(lp);
tvRight.setBackgroundColor(Color.WHITE);
tvRight.setText("WORKED!!!");
tr.addView(tvLeft);
tr.addView(tvCenter);
tr.addView(tvRight);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
回答2:
I think you want to create your TextView dynamically and should're getting error "removeView () parent." Here is a good solution for that:
TableView tlSkills = (TableView) findViewById(R.id.myTableView);
if(listSkills.size() > 0) {
TableRow tableRow = new TableRow(getContext());
int i = 0;
for (Skills s : listSkills) {
TextView textView = new TextView(getContext());
textView.setText("" + s.getName());
tableRow.addView(textView);
if(i > 0) {
tlSkills.removeView(tableRow);//this is to avoid the error I mentioned above.
}
tlSkills.addView(tableRow);
i++;
}
}
来源:https://stackoverflow.com/questions/15458495/android-adding-more-than-one-textview-to-a-tablerow-programmatically