I am getting stucked on the following problem: For a questions app I want to implement a nice output for a survey showing the possible answers and the percentage of people answered the specific question. Therefore, I want to add a "bar" to my app that displays the percentage. I try to solve this by using views and weighting them in a linear layout.

I want to add the different answers programmatically, this is the code I've got so far. My problems are, that I am not getting closer to weighting the views and resizing them.

/* Add all questions */ 
RelativeLayout my_root = (RelativeLayout) findViewById(R.id.ownerRL);

/* Add a new Linearlayout as a container for the question */
LinearLayout A = new LinearLayout(this);
A.setOrientation(LinearLayout.HORIZONTAL);
my_root.addView(A);

/* Create a new View in this container, for the status bar */
View new_view = new View(getBaseContext());
new_view.setBackgroundColor(Color.YELLOW);

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(50, 20, 3);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) A.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.question1);   

A.addView(new_view);
View new_view2 = new View(getBaseContext());
new_view.setBackgroundColor(Color.GREEN);
ViewGroup.LayoutParams lp2 = new ViewGroup.LayoutParams(50, 20);
RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) A.getLayoutParams();
params2.addRule(RelativeLayout.BELOW, R.id.question1);  
params2.addRule(RelativeLayout.LEFT_OF, new_view.getId());

A.addView(new_view2);

The Green view should actually be right of the yellow one (which is not visible).

How do get it managed such that it creates a red/white bar that has a height of 4px and the red and weight parts are weighted?

Thanks for your help!

有帮助吗?

解决方案

check this link, Set Linear Layout weight it like this

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT, 1.0f);

The last parameter is weight.Hope this help.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top