2013-01-01 26 views
0

我已经做了线性布局和添加视图,但是,视图出现两次,我不知道为什么会发生。可以修复它吗? 我有关于适配器的问题,我看了几次,我发现这里没有什么奇怪的。但是我删除了addView语句,它不会出现之前添加过的任何视图。适配器上的Double AddView

public View getView(int position, View convertView, ViewGroup parent) { 
    // TODO Auto-generated method stub 
    if(convertView == null) 
    { 
     LayoutInflater inflater = LayoutInflater.from(parent.getContext()); 
    // inflater.inflate(R.layout. parent,false); 
     convertView = inflater.inflate(R.layout.exerciseui_item,parent,false); 

    } 
    Exercise question = exercises.get(position); 
    TextView question_view = (TextView) convertView.findViewById(R.id.exercise_question); 
    String question_test = question.getOrder() + " " + question.getText() ; 
    question_view.setText(question_test); 
    int answer_num = question.getAnswer().size(); 

    LinearLayout linear = (LinearLayout) convertView.findViewById(R.id.exercise_answer); 
     ExerciseAnswer answer = question.getAnswer().get(0); 
     int answer_order = answer.getOrder(); 
     String answer_text = answer.getText(); 
     String answer_final = answer_order + " " + answer_text; 
     TextView answer_view = new TextView(linear.getContext()); 
     answer_view.setPadding(20, 5, 5, 5); 
     answer_view.setTextSize(30); 
     answer_view.setText(answer_final); 
     linear.addView(answer_view); 


    return convertView; 
} 

以下是exerciseui_item

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
android:id="@+id/exercise_answer" > 

<TextView 
    android:id="@+id/exercise_question" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 

    android:textSize="13dp" 
    ></TextView> 
</LinearLayout> 
+0

你如何将视图添加到线性布局? – Faizan

+0

我想通过在convertView上查找线性布局将视图添加到线性布局中。然后,我在其上添加视图 – user1494052

回答

0

这听起来像视图重新循环可能是这背后的XML。您的适配器负责创建数据集中每个项目的视图(这就是getView方法的目的)。为了节约资源,Android会重新循环观看。这就是getView方法传递View的原因。如果传入的视图是非空的,那意味着它已经被用来在这个列表中显示数据。

因此,“清理”视图是适配器的责任。在你的情况下,这意味着你必须考虑到你可能已经动态地将TextView元素添加到这个视图(在以前的getView调用中)。未能“清理”视图意味着每次视图重新循环时,您的方法都会将另一个TextView添加到布局。

你的情况,我会建议搜索LinearLayout的答案TextEdit。 (给这个TextEdit一个id,以便你可以通过使用findViewById()来找到它)。如果它已经存在,那么你不需要添加它。

另一种方法是在XML布局中包含第二个TextEdit权限。我不清楚为什么需要动态添加。

+0

因为要求是在不同的问题中有不同数量的答案。我需要动态添加它。当然,我可以使用for循环执行此操作,但我想知道是否有办法通过使用适配器来执行此操作。 – user1494052

+0

如果要为每行添加不同数量的TextView,仍然可以优雅在getView()中处理。我建议,首先查找并删除布局中的所有现有TextView。然后添加您需要的TextViews的数量。查看ViewGroup API:http://developer.android.com/reference/android/view/ViewGroup.html。看看addView/removeView系列的方法。 – EJK