问题
I want to add a view comprising of 4 buttons and a textview to a linear layout and set that newly made view to a viewflipper...Client's requirement is that i need to create the layout the programmatically and not using an xml file
回答1:
See this is sample code, this might helpful for you. Instaed of LockView you can mention other views..
lockLayout = (LinearLayout) findViewById(R.id.quick_lock_layout);
private void renderLockLayout() {
lockLayout.removeAllViews();
lockLayout.invalidate();
lockLayout.setLayoutParams(new LinearLayout.LayoutParams(
lockLayoutWidth + 7, (height / 6)));
/*
* Toast.makeText(ApplicationContext.getContext(), "Num count is :" +
* _totalLocks, Toast.LENGTH_SHORT).show();
*/
Log.i(getClass().getSimpleName(), "Total :" + _totalLocks);
lockViewArray = new LockView[_totalLocks];
for (int index = 0; index < _totalLocks; index++) {
LockView lockview = (LockView) inflater.inflate(R.layout.lockview,
null);
lockview.setLayoutParams(new LayoutParams((width),
LayoutParams.WRAP_CONTENT));
lockLayout.addView(lockview);
lockViewArray[index] = lockview;
}
lockLayout.invalidate();
}
回答2:
It's recommended to define UI in XMl. But for your client requirement you can do it dynamically. In android, UI in xml and at run time (.java file) are optional each other. So use java methods to create LinearLayout and add newly created views to it. Finally you can add this LinearLayout to ViewFlipper.
来源:https://stackoverflow.com/questions/14826822/adding-multiple-views-to-a-view