【问题标题】:Dynamic horizontal scroll view in AndroidAndroid中的动态水平滚动视图
【发布时间】:2011-12-29 07:13:41
【问题描述】:

我想要这个:我正在构建几个屏幕,在那里我会遇到诸如

之类的问题
1.The capital of India is
a. Delhi
b. Bangalore
c. Chennai

2. Are you sure?
a. Yes
b. No

现在我想要的就是在一个屏幕上我想要问题 1,在滑动(水平滚动)时我应该看到问题 2。选项必须是单选按钮。作为一个 Android 菜鸟,我知道我必须使用水平滚动,但我可能在一个 sqlite 文件中有 100 个这样的问题:我如何动态地做到这一点?一旦我调用了活动,就必须从文件中读取 100 个问题,并且我应该有 100 个这样的可滚动屏幕。帮助,我在 android 开发网站或这里找不到太多关于此的信息。

【问题讨论】:

    标签: android horizontal-scrolling horizontalscrollview


    【解决方案1】:

    如前所述,最好的选择是聆听滑动手势并替换视图中的数据。 即您不需要为每个问题创建多个视图。 这是我会做的: 创建一个xml或多或少类似的视图(请注意我跳过了包括layoutheight和layoutwidth之类的mandetory属性,你需要在xml中使用它们)

    <LinearLayout
      android:orientation="vertical">
       <TextView
          android:id="+@id/questiontext"/>
       <RadioGroup
          android:id="+@/answersgroup"/>
    </LinearLayout>
    

    现在在活动中:

    1. 实现触摸监听器并编写代码来检测滑动。 (ali.chousein 的上述答案包含完美的链接,以获得有关如何做的良好参考)。
    2. 在初始加载时将第一个问题设置为视图:

      QandA_CustomDataObject dataItem = questionArr.get(0);
      ((TextView)findViewById(R.id.questiontext)).setText(dataItem.question);
      int answearrsize = dataItem.answers.size();
      RadioGroup rg = ((RadioGroup)findViewById(R.id.answersgroup));
      for(int i=0;i<answearrsize;i++) //Dynamically create the radio buttons
      {
          AnswerObj ao = dataItem.get(0).answers.get(i);
          RadioButton rb = new RadioButton(this);
          rb.setText(ao.text);
          rb.setTag(ao.isCorrectAnswer); //A string saying TRUE or FALSE
          rg.addView(rb);
      }
      
    3. 现在在您对向右滑动或向左滑动执行手势验证后的代码部分

      //Lets say you ++ or -- a variable named currentQuestionNumber based on the swipe direction)
      QandA_CustomDataObject dataItem = questionArr.get(currentQuestionNumber);
      ((TextView)findViewById(R.id.questiontext)).setText(dataItem.question);
      int answearrsize = dataItem.answers.size();
      RadioGroup rg = ((RadioGroup)findViewById(R.id.answersgroup));
      rg.removeAllViews(); //Clears away the last questions answer options
      for(int i=0;i<answearrsize;i++) //Dynamically create the radio buttons
      {
          AnswerObj ao = dataItem.get(0).answers.get(i);
          RadioButton rb = new RadioButton(this);
          rb.setText(ao.text);
          rb.setTag(ao.isCorrectAnswer); //A string saying TRUE or FALSE
          rg.addView(rb);
      }         
      

    现在有几种替代方法可以做到这一点。使用适配器、列表视图等。 我随意命名了所有数据结构类,但我希望你明白这一点.. 它更多的是使用我想指出的相同 Activity(Screen) 来处理从一个问题转移到另一个问题的方法。

    【讨论】:

    • 谢谢!!!我现在就试试这个——我有一个存储我的数据的 sqlite 文件,所以我需要与之同步——你能告诉我我该怎么做以及那段代码应该在哪里吗?
    【解决方案2】:

    您为什么不检测滑动手势并更改活动内容,而不是水平视图?您可以找到许多关于检测滑动手势的指针。其中之一是:Fling gesture detection on grid layout

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多