在我的视图中,我想在tablerow视图中添加imageview,它在列表视图中膨胀,因此我可以在列表视图中动态添加imageview,但我无法动态添加表行。请帮我解决这个问题。
这是类文件:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView imagegrid = (ListView) findViewById(R.id.listView1);
imagegrid.setAdapter(new ImageAdapter(this));
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Activity mContext;
public ImageAdapter(Activity mainActivity) {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = mainActivity;
}
public int getCount() {
return 10;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View customRow = mInflater.inflate(R.layout.row, null);
TableLayout tl = (TableLayout) customRow.findViewById(R.id.scroll);
/* Create a new row to be added. */
TableRow tr = new TableRow(mContext);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
/*
* Create view to add view to row, here i am adding only button you
* can andd any view you want
*/
Button b = new Button(mContext);
b.setText("Dynamic Button");
b.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
/* Add Button to row. */
tr.addView(b);
/* Add row to TableLayout. */
tl.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
return customRow;
}
}
这是我的xml文件....
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/scroll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="0dp"
android:orientation="vertical" >
答案 0 :(得分:0)
您需要执行以下步骤
TableLayout tl = (TableLayout)findViewById(R.id.yourtbllayout);
/* Create a new row to be added. */
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
/*Create view to add view to row, here i am adding only button you can andd any view you want*/
Button b = new Button(this);
b.setText("Dynamic Button");
b.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
/* Add Button to row. */
tr.addView(b);
/* Add row to TableLayout. */
tl.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));