使用appcompat-v21在片段内扩展列表视图

时间:2014-10-28 19:39:02

标签: android android-fragments expandablelistview android-appcompat expandablelistadapter

我正在为学校编写一个小应用程序。这个概念很简单:从学校网站下载数据,将它们放在json中并用片段显示它们。每个片段都由相同的FrameLayout托管。使用ListFragments一切顺利,但我需要在里面添加一个包含expandablelistview的片段。这里出现了问题。 首先,我必须把

  

查看rootView = inflater.inflate(R.layout.activity_dettaglio,containerObject,false);

而不是

  

查看rootView = inflater.inflate(R.layout.activity_dettaglio,containerObject);

因为它导致了这个错误

  

指定的孩子已经有父母。您必须首先在孩子的父母上调用removeView()。   java.lang.IllegalStateException:指定的子节点已经有了   家长。您必须先在孩子的父母身上调用removeView()。

通过这种方式问题得以解决,但在运行应用程序时,我在工具栏和expandablelistview的开头之间看到了一个意外的空间。我找不到问题。

第二个问题非常烦人:expandablelistview显示组之间的白色分隔符,但当我展开其中一个时,分隔符几乎消失。我将分隔线颜色设置为透明/ @null /背景颜色,但白线仍然存在。我尝试了很多方法,但我找不到解决问题的方法。

我要在这里写下我的代码中涉及的部分:

public class DettaglioFragment extends Fragment {
public List<String> materie;
public List<String> materie_long;
public ExLiADettaglio adapter;
public ExpandableListView explist;
public HashMap<String, Integer> objectives = new HashMap<String, Integer>();
protected SharedPreferences prefs;
protected SharedPreferences prefsMaterie;
protected HashMap<String, List<Voto>> listData;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup containerObject, Bundle savedInstanceState) {
    Log.d("Debug", "DettaglioFragment started...");
    ((MainActivity)getActivity()).ChangeColor(getResources().getColor(R.color.blu_scuro));
    View rootView = inflater.inflate(R.layout.activity_dettaglio, containerObject, false);  //TODO raddoppia la barra
 //   ((MainActivity) getActivity()).getSupportActionBar().setTitle("Dettaglio Voti");
    Bundle bundle = getArguments();

    prefs = getActivity().getSharedPreferences("obbiettivi", Context.MODE_PRIVATE);
    prefsMaterie = getActivity().getSharedPreferences("materie", Context.MODE_PRIVATE);

    try {
        JSONArray array = new JSONArray(bundle.getString("voti"));
        materie = new ArrayList<String>();
        materie_long = new ArrayList<String>();
        listData=new HashMap<String, List<Voto>>();
        for (int i=0; i<array.length(); i++){
            JSONObject temp=array.getJSONObject(i);
            String nome=temp.getString("nome");
            materie_long.add(nome);
            materie.add(MateriaShortener(nome));
            JSONArray array2=temp.getJSONArray("voti");
            List<Voto> listTemp=new ArrayList<Voto>();
            for (int j=0; j<array2.length();j++){
                JSONObject temp2=array2.getJSONObject(j);
                listTemp.add(new Voto(temp2));
            }
            listData.put(MateriaShortener(nome), listTemp);
        }
    } catch (JSONException e){
        e.printStackTrace();
    }

    for (int i = 0; i < materie.size(); i++)
        objectives.put(materie.get(i), prefs.getInt(materie_long.get(i), 6));

    adapter = new ExLiADettaglio(getActivity(), new ArrayList<String>(0), new HashMap<String, List<Voto>>(), objectives);

    explist = (ExpandableListView) rootView.findViewById(R.id.expListView);

    adapter.Modifica(getActivity(), materie, listData);

    return rootView;

}

@Override
public void onViewCreated(View view, Bundle savedInstanceState){

    explist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d("Debug", "LongClick");
            int itemType = ExpandableListView.getPackedPositionType(id);
            final int pos = position;
            switch (itemType) {
                case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
                    return false;
                case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
                    int preselected = prefs.getInt(materie_long.get(position), 6) - 6;
                    CharSequence[] array = {"6", "7", "8", "9", "10"};
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                    builder.setTitle("Seleziona l'obbiettivo: ")
                            .setSingleChoiceItems(array, preselected, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    boolean ok;
                                    SharedPreferences.Editor editor = prefs.edit();
                                    editor.putInt(materie_long.get(pos), which + 6);
                                    ok = editor.commit();
                                    if (!ok)
                                        Log.e("Debug", "DettaglioActivity.OnItemLongClickListener.OnClick --- salvataggio non riuscito");
                                    Aggiorna();
                                    dialog.dismiss();
                                }
                            });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return true;
                default:
                    Log.e("Debug", "Neither child nor group?? OMFG WTF!?");
                    return true;
            }
        }
    });

    explist.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            Log.d("Debug", "(" + groupPosition + " , " + childPosition + ") clicked");
            Voto child = (Voto) adapter.getChild(groupPosition, childPosition);
            if (child.getNota().equals("\u00A0"))
                return false;
            else {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                builder.setTitle(materie.get(groupPosition) + " " + child.getStringa() + " " + child.getTipo())
                        .setMessage(child.getNota())
                        .setNeutralButton("Indietro", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
            }
        }
    });
    explist.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener(){
        int precedente=-1;

        @Override
        public void onGroupExpand(int groupPosition){
            if(groupPosition != precedente && precedente>=0){
                explist.collapseGroup(precedente);
            }
            precedente = groupPosition;
        }

    });

    explist.setAdapter(adapter);
}

public void Aggiorna (){
    objectives.clear();
    for (int i=0; i<materie.size(); i++)
        objectives.put(materie.get(i), prefs.getInt(materie_long.get(i), 6));
    adapter.CambiaObjectives(objectives);
    explist.setAdapter(adapter);
//    adapter.notifyDataSetChanged();

}


protected String MateriaShortener (String a){
    return prefsMaterie.getString(a, a);
}
}

public class ExLiADettaglio extends BaseExpandableListAdapter {
    protected Context _context;
    protected List<String> _listDataHeader; // header titles
    // child data in format of header title, child title
    protected HashMap<String, List<Voto>> _listDataChild;
    protected HashMap<String, Integer> objectives;

 //   protected ShapeDrawable cerchio;

    public ExLiADettaglio(Context context, List<String> listDataHeader,
            HashMap<String, List<Voto>> listChildData, HashMap<String, Integer> objectives) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
        this.objectives=objectives;
 //       InizializzaDrawable();
    }

    public void Modifica(Context context, List<String> listDataHeader,
            HashMap<String, List<Voto>> listChildData) {
        this._context = context;
        this._listDataHeader = listDataHeader;
        this._listDataChild = listChildData;
    }

   public void CambiaObjectives (HashMap<String, Integer> objectives){
       this.objectives=objectives;
   }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {
        String headerTitle = (String) getGroup(groupPosition);
        int size=getChildrenCount(groupPosition);

        double rif=objectives.get(getGroup(groupPosition));
        double media=Media(groupPosition);

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_group2, null);
        }

        TextView nome_materia = (TextView) convertView.findViewById(R.id.nome_materia);
        nome_materia.setTypeface(null, Typeface.BOLD);
        nome_materia.setText(headerTitle);

        TextView media_voti=(TextView) convertView.findViewById(R.id.media_voti);
//        media_voti.setTypeface(null, Typeface.BOLD);

        TextView note=(TextView) convertView.findViewById(R.id.note);

        View cerchio=(View) convertView.findViewById(R.id.img);

        if (size==0){
            media_voti.setText("ND");
            note.setText("Nessun voto trovato");
            setColor(Color.parseColor("#808080"), cerchio);
        }
        else {
            if (media<10) {
                media_voti.setText(String.valueOf(media));
            } else {
                media_voti.setText("10");
            }
            setColor(new ColoreVoto(media, rif).getColor(), cerchio);
            note.setText(Nota(size, media, rif));
        }

        RelativeLayout linearLayout=(RelativeLayout) convertView.findViewById(R.id.linlay);
        /*if (isExpanded){
            linearLayout.setBackgroundColor(_context.getResources().getColor(R.color.blu_scuro));
            nome_materia.setTextColor(_context.getResources().getColor(R.color.drawer_text_dark));
            media_voti.setTextColor(_context.getResources().getColor(R.color.drawer_text_dark));
            note.setTextColor(_context.getResources().getColor(R.color.drawer_text_dark));
        }else{
            linearLayout.setBackgroundColor(_context.getResources().getColor(android.R.color.white));
            nome_materia.setTextColor(_context.getResources().getColor(R.color.drawer_text));
            media_voti.setTextColor(_context.getResources().getColor(R.color.drawer_text));
            note.setTextColor(_context.getResources().getColor(R.color.drawer_text));
        }*/

        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, final int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {
        final Voto childVoto = (Voto) getChild(groupPosition, childPosition);
        double rif=objectives.get(getGroup(groupPosition));

        if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this._context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.list_item2, null);
        }

        TextView voto = (TextView) convertView.findViewById(R.id.voto);
        voto.setText(childVoto.getStringa());

        TextView tipo = (TextView) convertView.findViewById(R.id.tipo);
        tipo.setText(childVoto.getTipo());

        TextView giorno = (TextView) convertView.findViewById(R.id.data);
        giorno.setText(childVoto.getData());

        View cerchio=(View) convertView.findViewById(R.id.img);
        setColor(new ColoreVoto(childVoto.getVoto(), rif).getColor(), cerchio);

        ImageView nota=(ImageView) convertView.findViewById(R.id.nota);
        if (childVoto.getNota().equals("\u00A0"))
            nota.setVisibility(View.GONE);
        else nota.setVisibility(View.VISIBLE);

        return convertView;
    }

/*    private void InizializzaDrawable(){
        cerchio = new ShapeDrawable();

        Shape s1 = new OvalShape();
        ((ShapeDrawable) cerchio).setShape(s1);
        setColor(Color.GRAY);

    }*/

    private void setColor (int color, View view){
        ((GradientDrawable)view.getBackground()).setColor(color);
       //  ((ShapeDrawable) cerchio).getPaint().setColor(color);
    }

    private double Media (int pos){
        double media=0;
        int size=getChildrenCount(pos);
        for (int i=0; i<size; i++){
            media+=(double)_listDataChild.get(_listDataHeader.get(pos)).get(i).getVoto();
        }
        media=media/size;
        media=Arrotonda(media);     
        return media;
    }

    protected String Nota (int size, double media, double rif){
        String nota;
        double voto;
        if (media>=rif){
            nota="Attento a non prendere meno di ";
        }
        else {
            nota="Per recuperare devi prendere almeno ";
        }
        voto=rif*(size+1)-media*size;
        voto=Arrotonda(voto);
        nota+=String.valueOf(voto);
        return nota;
    }


    protected double Arrotonda(double n){
        return ((double) Math.round(n*100))/100;
    }


    @Override
    public Object getChild(int groupPosition, int childPosititon) {
    //  Log.d("Debug", "getChild");
        return this._listDataChild.get(this._listDataHeader.get(groupPosition))
                .get(childPosititon);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        Log.d("debug", "groupposition: "+groupPosition);
        String parent=this._listDataHeader.get(groupPosition);
        Log.d("debug", "parent: "+parent);
        List<Voto> children=this._listDataChild.get(parent);
        Log.d("debug", "children: "+children);
        return children.size();
    //  return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._listDataHeader.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._listDataHeader.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

}

dettaglio_fragment.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent">
<ExpandableListView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:id="@+id/expListView"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:childDivider="@android:color/transparent"
    android:dividerHeight="0dp"/>

list_group2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linlay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dp"
    android:layout_marginRight="5dp"
    card_view:cardCornerRadius="0dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="4dp"
        android:paddingBottom="4dp">
        <TextView
            android:id="@+id/nome_materia"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/media_voti"
            android:paddingLeft="20dp"
            android:textColor="@android:color/black"
            android:textSize="20dp"
            android:textStyle="bold"
            android:text="Matematica" />

        <TextView
            android:id="@+id/media_voti"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAlignment="center"
            android:textSize="30dp"
            android:text="9.5"
            android:paddingRight="15dp"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/img"
            android:textStyle="bold"
            android:textColor="@android:color/black"/>

        <View
            android:id="@+id/img"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_marginRight="4dp"
            android:background="@layout/circle"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            />

        <TextView
            android:id="@+id/note"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignRight="@+id/nome_materia"
            android:layout_below="@+id/nome_materia"
            android:paddingLeft="20dp"
            android:text="Attento a non prendere meno di 2.5"
            android:textSize="10dp"
            android:textStyle="italic"
            android:textColor="@android:color/black"/>
    </RelativeLayout>
</android.support.v7.widget.CardView>

list_item2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="0dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingTop="4dp"
        android:paddingBottom="4dp">

        <TextView
            android:id="@+id/data"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="27/09/14"
            android:layout_alignParentLeft="true"
            android:paddingLeft="7dp"
            android:textSize="20dp"
            android:textColor="@android:color/black"/>
        <TextView
            android:id="@+id/tipo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(Scritto)"
            android:textSize="20dp"
            android:layout_marginLeft="20dp"
            android:layout_toRightOf="@+id/data"
            android:layout_centerVertical="true"
            android:textColor="@android:color/black"/>

        <TextView
            android:id="@+id/voto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toLeftOf="@id/img"
            android:layout_centerVertical="true"
            android:layout_marginRight="30dp"
            android:text="7+"
            android:textSize="20dp"
            android:textStyle="bold"
            android:textColor="@android:color/black"/>

        <View
            android:id="@+id/img"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:background="@layout/circle"
            android:layout_alignParentRight="true"
            android:layout_marginRight="7dp"/>

        <ImageView
            android:id="@+id/nota"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:src="@drawable/nota"
            android:layout_centerVertical="true"
            android:layout_toStartOf="@id/img"
            android:padding="4dp"
            android:layout_marginRight="5dp"
            android:layout_alignTop="@id/img"
            android:background="@android:color/transparent"
            android:visibility="visible"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/masterContainerLinear"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blu_scuro">

<include
    android:id="@+id/toolbar"
    layout="@layout/toolbar"
    />

<android.support.v4.widget.DrawerLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:id="@+id/drawer_layout">

    <!--  MAIN ACTIVITY -->

        <FrameLayout
            android:id="@+id/swipe_container"
            android:layout_height="match_parent"
            android:layout_width="match_parent">
        </FrameLayout>

    <!-- DRAWER -->

    <FrameLayout
        android:layout_height="match_parent"
        android:layout_width="@dimen/drawer_width"
        android:id="@+id/drawer_list_container"
        android:layout_gravity="start"
        android:background="@android:color/white">

        <ExpandableListView
            android:layout_height="fill_parent"
            android:layout_width="fill_parent"
            android:id="@+id/drawer_list"
            android:layout_gravity="start"
            android:choiceMode="singleChoice"
            android:scrollbars="none"
            android:divider="@null"
            android:dividerHeight="0dp"/>

    </FrameLayout>

</android.support.v4.widget.DrawerLayout>

toolbar.xml

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"
android:elevation="5dp"/>

MainActivity.java - DettaglioFragment的归档

DettaglioFragment fragment=new DettaglioFragment();
Bundle bundle = new Bundle();
bundle.putString("voti", jsonObject.getJSONObject("voti").getJSONArray("array").toString());
fragment.setArguments(bundle);
FragmentManager fm=getFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.swipe_container, fragment);
transaction.commit();
break;

MainActivity的其余部分不应该如此相关,因为它包含用于启动其他片段并初始化变量的代码并且它很长(它是600行)所以我不会把它放在这里。 最后但并非最不重要的是,我将在这里放下一张照片,显示我遇到的两个布局问题。 https://www.dropbox.com/s/x0b4xbks9ivq0r9/Screenshot_2014-10-28-19-59-01.png?dl=0

0 个答案:

没有答案