how to get percentage scrolled by the user?

2019-04-02 04:31发布

问题:

i have a scrollview with text in it and a button at the bottom. what i want to do is change the text on the button according to the percentage of scrolling done by the user. this is my code:

public class Verbal extends Activity implements ScrollViewListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.verbal);
    ObservableScrollView scrollview = (ObservableScrollView) findViewById(R.id.scrollview);
    scrollview.setScrollViewListener(this);

}

@Override
public void onScrollChanged(ObservableScrollView scrollView, int x, int y,
        int oldx, int oldy) {
    // TODO Auto-generated method stub
    Button answer = (Button) findViewById(R.id.answernumber);

    int totalHeight = scrollView.getChildAt(0).getHeight();
    int p = (y/totalHeight)*100;

    if (p>3 && p<8)
        answer.setText("1");
    else if (p>8 && p<11)
        answer.setText("2");
    else if (p>11 && p<14)
        answer.setText("3");
    else if (p>14 && p<17)
        answer.setText("4");
    else if (p>17 && p<21) 
        answer.setText("5");
    else if (p>21 && p<25)
        answer.setText("6");
    else if (p>25 && p<29)
        answer.setText("7");
    else if (p>29 && p<31)
        answer.setText("8");
    else if (p>31 && p<35)
        answer.setText("9");
    else if (p>35 && p<39)
        answer.setText("10");
    else if (p>39 && p<45)
        answer.setText("11");
    else if (p>45 && p<50)
        answer.setText("12");
    else if (p>50 && p<56)
        answer.setText("13");
    else if (p>56 && p<62)
        answer.setText("14");
    else if (p>62 && p<67)
        answer.setText("15");
    else if (p>67 && p<72)
        answer.setText("16");
    else if (p>72 && p<78)
        answer.setText("17");
    else if (p>78 && p<83)
        answer.setText("18");
    else if (p>83 && p<86)
        answer.setText("19");
    else if (p>86)
        answer.setText("20");   




}

}

the problem is the text is not changing in the button because initially the value of 'y' is zero so 'p' is also zero. but as the user scrolls down value of 'y' changes and 'p' dosent change. i need to continuously change value of 'p' as 'y' changes. please help me programmatically what to do?

回答1:

I think your problem is that you're running a integer division, and thus p is always 0. You have to cast it to double like this:

 double p = ((double)y/(double)totalHeight)*100;