【问题标题】:Setting ListView two times in Fragment Class在 Fragment 类中设置 ListView 两次
【发布时间】:2016-12-16 21:39:54
【问题描述】:

我在数据库中有一个名为“类别”的基本表。那么另外两个表Category1 和Category2 都和category 表是一对多的关系。它是这样的:-

**Category Table**
Id    Category
0     Category1 (One) -> Category1 Table (Many).
1     Category2 (One) -> Category2 Table (Many).

我正在使用选项卡管理器,它将显示类别表中的两个类别以及列表视图中的项目列表,该选项卡在 category1 或 category2 表的一个选项卡中,另一个在另一个选项卡中。但我面临的问题是我试图根据 if-else 语句在 listview 上设置适配器。因此,当我按下选项卡上的 category2 时,它只显示 category1 项目而不是 category2 项目。 我知道根据我所做的研究,我不能在一个列表视图中设置两个适配器。有什么解决办法吗?下面是我的代码。

片段类

public class CategoryFragment extends Fragment{

    private ListView listView;
    private String currentTabTag;
    private CategoryAdapter1 categoryAdapter1;
    private CategoryAdapter2 categoryAdapter2;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // inflate the layout for this fragment
        View view = inflater.inflate(R.layout.activity_category_fragment_list, container, false);

        // get references to widgets
        listView = (ListView) view.findViewById (R.id.prescriptorsListView);

        // get the current tab
        TabHost tabHost = (TabHost) container.getParent().getParent();
        currentTabTag = tabHost.getCurrentTabTag();

        // refresh the category list view
        refreshCategoryList();

        // return the view
        return view;
    }

    public void refreshCategoryList() {
        // get category list for current tab from database
        Context context = getActivity().getApplicationContext();
        CategoryDatabase categoryDatabase = new CategoryDatabase(context);

        if(currentTabTag.equals("Category 1")) {
            ArrayList<Category1> category1ArrayList = categoryDatabase.getAllCategory1(currentTabTag);
            // create adapter and set it in the ListView widget
            listView = new Category1Adapter(context, category1ArrayList);
            listView.setAdapter(Category1Adapter);
        }
        else if(currentTabTag.equals("Category 2"))
        {
            ArrayList<Category2> category2ArrayList = categoryDatabase.getAllCategory2(currentTabTag);
            // create adapter and set it in the ListView widget
            listView = new Category2dapter(context, category2ArrayList);
            listView.setAdapter(Category2Adapter);
        }

    }
    @Override
    public void onResume() {
        super.onResume();
        refreshTaskList();
    }
}

Category1的适配器

public class Category1Adapter extends BaseAdapter {
    private Context context;
    private ArrayList<Category1> category1ArrayList;

    public Category1Adapter(Context context, ArrayList<FamilyPrescription> category1ArrayList) {
        this.context = context;
        this.category1ArrayList = category1ArrayList;
    }

    @Override
    public int getCount() {
        return category1ArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return category1ArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Category1TaskLayout taskLayout = null;
        Category1 category1 = category1ArrayList.get(position);

        if (convertView == null) {
            taskLayout = new Category1TaskLayout(context, category1);
        } else {
            taskLayout = (Category1TaskLayout) convertView;
            taskLayout.setCategory1(category1);
        }
        return taskLayout;
    }
}

category2的适配器与上面的适配器类似。

任何帮助将不胜感激:)

【问题讨论】:

  • 如果你有一个ListView,你应该使用一个适配器来管理标签更改(adapter.notifyDataSetChanged()
  • 如果可能的话,你能解释一下如何使用上面的例子吗

标签: android mysql listview android-fragments


【解决方案1】:

按照我的建议,我考虑过使用一个适配器。

private class OneAdapter extends BaseAdapter {

    List<Category1> cat1 = categoryDatabase.getAllCategory1(currentTabTag);
    List<Category2> cat2 = categoryDatabase.getAllCategory2(currentTabTag);

    @Override
    public int getCount() {
        if(currentTabTag.equals("Category 1")) {
            return cat1.size();
        } else if(currentTabTag.equals("Category 2")) {
            return cat2.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if(currentTabTag.equals("Category 1")) {
            return cat1.get(position);
        } else if(currentTabTag.equals("Category 2")) {
            return cat2.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        //...

        Object c = getItem(position);
        if(c instanceof Category1) {
            ...
        } else if(c instanceof Category2) {
            ...
        }

        return convertView;
    }
}

随着tab改变需要更新adapter;

    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            currentTabTag = tabHost.getCurrentTabTag();
            adapter.notifyDataSetChanged();
        }
    });

Activity 中的完整工作示例:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends AppCompatActivity {

    TabHost tabHost;
    ListView listView;
    String currentTabTag;
    CategoryDatabase categoryDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);

        tabHost = (TabHost) findViewById(android.R.id.tabhost);
        tabHost.setup();
        TabHost.TabSpec tab1 = tabHost.newTabSpec("Category 1");
        TabHost.TabSpec tab2 = tabHost.newTabSpec("Category 2");
        tab1.setContent(R.id.tab1);
        tab1.setIndicator("Cat1");
        tab2.setContent(R.id.tab2);
        tab2.setIndicator("Cat2");
        tabHost.addTab(tab1);
        tabHost.addTab(tab2);

        categoryDatabase = new CategoryDatabase();

        currentTabTag = tabHost.getCurrentTabTag();

        listView = (ListView) findViewById(android.R.id.list);

        listView.setAdapter(new TabAdapter());
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                currentTabTag = tabHost.getCurrentTabTag();
                ((BaseAdapter)listView.getAdapter()).notifyDataSetChanged();
            }
        });
    }

    private class TabAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if(currentTabTag.equals("Category 1")) {
                return categoryDatabase.getAllCategory1().size();
            } else if(currentTabTag.equals("Category 2")) {
                return categoryDatabase.getAllCategory2().size();
            }
            return 0;
        }

        @Override
        public Object getItem(int position) {
            if(currentTabTag.equals("Category 1")) {
                return categoryDatabase.getAllCategory1().get(position);
            } else if(currentTabTag.equals("Category 2")) {
                return categoryDatabase.getAllCategory2().get(position);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if(convertView == null) {
                convertView = LayoutInflater.from(Main2Activity.this).inflate(android.R.layout.simple_list_item_1, parent, false);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            Object c = getItem(position);
            if(c instanceof Category1) {
                Category1 c1 = (Category1) c;
                holder.text1.setText(c1.text);
            } else if(c instanceof Category2) {
                Category2 c2 = (Category2) c;
                holder.text1.setText(c2.text);
            }

            return convertView;
        }

        class ViewHolder {
            TextView text1;
            public ViewHolder(View convertView) {
                text1 = (TextView) convertView.findViewById(android.R.id.text1);
            }
        }
    }
}

class CategoryDatabase {
    private List<Category1> cat1;
    private List<Category2> cat2;
    {
        cat1 = new ArrayList<Category1>();
        cat2 = new ArrayList<Category2>();
        for(int i=0;i<10;i++) {
            cat1.add(new Category1("Category 1 "+i));
        }
        for(int i=0;i<20;i++) {
            cat2.add(new Category2("Category 2 "+i));
        }
    }

    public List<Category1> getAllCategory1() {
        return cat1;
    }
    public List<Category2> getAllCategory2() {
        return cat2;
    }
}

class Category1 {
    String text;
    public Category1(String text) {
        this.text = text;
    }
}

class Category2 {
    String text;
    public Category2(String text) {
        this.text = text;
    }
}

布局:

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

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="5dp">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

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

                <View
                    android:id="@+id/tab1"
                    android:layout_width="match_parent"
                    android:layout_height="0dp" />

                <View
                    android:id="@+id/tab2"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"></View>
            </FrameLayout>
        </LinearLayout>

    </TabHost>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_weight="1"
        android:layout_height="0dp" />
</LinearLayout>

【讨论】:

    【解决方案2】:

    所以经过大量研究,我终于让我的标签正常工作了。我使用了 CWAC 合并适配器,感兴趣的人可以在 github link 中找到它。

    这是我在代码中使用它的方式:

    片段类

    public class CategoryFragment extends Fragment{
    
        private ListView listView;
        private String currentTabTag;
        private CategoryAdapter1 categoryAdapter1;
        private CategoryAdapter2 categoryAdapter2;
        private MergeAdapter adapter = new MergeAdapter();
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            // inflate the layout for this fragment
            View view = inflater.inflate(R.layout.activity_category_fragment_list, container, false);
    
            // get references to widgets
            listView = (ListView) view.findViewById (R.id.prescriptorsListView);
    
            // get the current tab
            TabHost tabHost = (TabHost) container.getParent().getParent();
            currentTabTag = tabHost.getCurrentTabTag();
    
            // refresh the category list view
            refreshCategoryList();
    
            // return the view
            return view;
        }
    
        public void refreshCategoryList() {
            // get category list for current tab from database
            Context context = getActivity().getApplicationContext();
            CategoryDatabase categoryDatabase = new CategoryDatabase(context);
    
            if(currentTabTag.equals("Category 1")) {
                ArrayList<Category1> category1ArrayList = categoryDatabase.getAllCategory1(currentTabTag);
                // create adapter and set it in the ListView widget
                categoryAdapter1 = new Category1Adapter(context, category1ArrayList);
                adapter.add(Category1Adapter);
            }
            else if(currentTabTag.equals("Category 2"))
            {
                ArrayList<Category2> category2ArrayList = categoryDatabase.getAllCategory2(currentTabTag);
                // create adapter and set it in the ListView widget
                categoryAdapter2 = new categoryAdapter2(context, category2ArrayList);
                adapter.add(categoryAdapter2);
            }
            listView.setAdapter(adapter);
    
        }
        @Override
        public void onResume() {
            super.onResume();
            refreshTaskList();
        }
    }
    

    我已经测试了这段代码,它可以工作。

    如果有人有更好的编码方式,请分享。

    快乐编码:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2015-10-07
      相关资源
      最近更新 更多