使用下拉菜单切换片段时,项目会继续添加到Listview

时间:2013-10-08 17:58:59

标签: android android-listview android-fragments

我按照这两个教程的代码使用ActionBarSherlock: http://www.androidbegin.com/tutorial/implementing-actionbarsherlock-search-collapsible-view-in-android/& http://www.androidbegin.com/tutorial/actionbarsherlock-custom-menu-list-navigation-fragments/

我遇到的问题是,每次使用下拉菜单切换片段时,相同的数据都会添加到列表视图中并继续添加每个开关。当点击列表视图中的数据打开SingleItemView然后返回列表视图时,也会发生同样的事情。任何人都可以给予任何帮助。

注意:我在搜索功能和操作栏中的按钮也是无关的。

MainActivity.java

public class MainActivity extends SherlockFragmentActivity {
// Declare Variables
NavListAdapter adapter;
EditText editsearch;
String[] title;
String[] subtitle;
Fragment fragment1 = new FiveHundred();
Fragment fragment2 = new OneThousand();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Generate title
    title = new String[] { "Title Fragment 1", "Title Fragment 2" };

    // Generate subtitle
    subtitle = new String[] { "Subtitle Fragment 1", "Subtitle Fragment 2" };


    // Pass results to NavListAdapter Class
    adapter = new NavListAdapter(this, title, subtitle);

    // Hide the ActionBar Title
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    // Create the Navigation List in your ActionBar
    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    // Listen to navigation list clicks
    ActionBar.OnNavigationListener navlistener = new OnNavigationListener() {

        @Override
        public boolean onNavigationItemSelected(int position, long itemId) {
            FragmentTransaction ft = getSupportFragmentManager()
                    .beginTransaction();
            // Locate Position
            switch (position) {
            case 0:
                ft.replace(android.R.id.content, fragment1);
                break;
            case 1:
                ft.replace(android.R.id.content, fragment2);
                break;
            }
            ft.commit();
            return true;
        }

    };
    // Set the NavListAdapter into the ActionBar Navigation
    getSupportActionBar().setListNavigationCallbacks(adapter, navlistener);
}

// Create the options menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Get the options menu view from menu.xml in menu folder
    getSupportMenuInflater().inflate(R.menu.search_layout, menu);

    // Locate the EditText in menu.xml
    editsearch = (EditText) menu.findItem(R.id.menu_search).getActionView();

    // Capture Text in EditText
    editsearch.addTextChangedListener(textWatcher);

    // Show the search menu item in menu.xml
    MenuItem menuSearch = menu.findItem(R.id.menu_search);

    menuSearch.setOnActionExpandListener(new OnActionExpandListener() {

        // Menu Action Collapse
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Empty EditText to remove text filtering
            editsearch.setText("");
            editsearch.clearFocus();
            return true;
        }

        // Menu Action Expand
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            // Focus on EditText
            editsearch.requestFocus();

            // Force the keyboard to show on EditText focus
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            return true;
        }
    });

    // Show the settings menu item in menu.xml
    MenuItem menuSettings = menu.findItem(R.id.menu_settings);

    // Capture menu item clicks
    menuSettings.setOnMenuItemClickListener(new OnMenuItemClickListener() {

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // TODO Auto-generated method stub
            // Do something here
            Toast.makeText(getApplicationContext(), "Nothing here!",
                    Toast.LENGTH_LONG).show();
            return false;
        }

    });

    return true;
}

// EditText TextWatcher
private TextWatcher textWatcher = new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        String text = editsearch.getText().toString()
                .toLowerCase(Locale.getDefault());
        adapter.filter(text);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }

};
}

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter
{
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Populate> populatelist = null;
private ArrayList<Populate> arraylist;

public ListViewAdapter(Context context, List<Populate> populatelist) 
{
    mContext = context;
    this.populatelist = populatelist;
    inflater = LayoutInflater.from(mContext);
    this.arraylist = new ArrayList<Populate>();
    this.arraylist.addAll(populatelist);
}

public class ViewHolder 
{
    TextView Name;
    TextView Value;

}

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

@Override
public Populate getItem(int position) 
{
    return populatelist.get(position);
}

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

public View getView(final int position, View convertView, ViewGroup parent) 
{
    final ViewHolder holder;
    if (convertView == null) 
    {
        holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.listview_item, null);
        // Locate the TextViews in listview_item.xml
        holder.Name = (TextView) convertView.findViewById(R.id.Name);
        holder.Value = (TextView) convertView.findViewById(R.id.Value);
        convertView.setTag(holder);
    }
    else 
    {

        holder = (ViewHolder) convertView.getTag();
    }
    // Set the results into TextViews
    holder.Name.setText(populatelist.get(position).getName());
    holder.Value.setText(populatelist.get(position).getValue());     

    // Listen for ListView Item Click
    convertView.setOnClickListener(new OnClickListener() 
    {
        public void onClick(View arg0) 
        {
            // Send single item click data to SingleItemView Class
            Intent intent = new Intent(mContext, SingleItemView.class);
            // Pass all data errorName
            intent.putExtra("Name",(populatelist.get(position).getName()));
            // Pass all data errorCode
            intent.putExtra("Value",(populatelist.get(position).getValue()));
            // Start SingleItemView Class
            mContext.startActivity(intent);
        }

    });
    return convertView;
}

// Filter Class
public void filter(String charText) 
{
    charText = charText.toLowerCase(Locale.getDefault());
    populatelist.clear();
    if (charText.length() == 0) 
    {
        populatelist.addAll(arraylist);
    }
    else
    {
        for (Populate p : arraylist)
        {
            // Search filter code
            if (p.getName().toLowerCase(Locale.getDefault()).contains(charText))
            {
                populatelist.add(p);
            }
            else if (p.getValue().toLowerCase(Locale.getDefault()).contains(charText))
            {
                populatelist.add(p);
            }
        }

    }       
    notifyDataSetChanged();
}

}

NavListAdapter.java

public class NavListAdapter extends BaseAdapter {

// Declare Variables
Context context;
String[] mTitle;
String[] mSubTitle;
LayoutInflater inflater;

public NavListAdapter(Context context, String[] title, String[] subtitle) {
    this.context = context;
    this.mTitle = title;
    this.mSubTitle = subtitle;
}

@Override
public int getCount() {
    return mTitle.length;
}

@Override
public Object getItem(int position) {
    return mTitle[position];
}

@Override
public long getItemId(int position) {
    return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView txtTitle;
    TextView txtSubTitle;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.nav_list_item, parent, false);

    // Locate the TextViews in nav_list_item.xml
    txtTitle = (TextView) itemView.findViewById(R.id.title);
    txtSubTitle = (TextView) itemView.findViewById(R.id.subtitle);

    // Set the results into TextViews
    txtTitle.setText(mTitle[position]);
    txtSubTitle.setText(mSubTitle[position]);
    return itemView;
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    // Declare Variables
    TextView txtTitle;
    TextView txtSubTitle;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View dropdownView = inflater.inflate(R.layout.nav_dropdown_item, parent,
            false);

    // Locate the TextViews in nav_dropdown_item.xml
    txtTitle = (TextView) dropdownView.findViewById(R.id.title);
    txtSubTitle = (TextView) dropdownView.findViewById(R.id.subtitle);

    // Set the results into TextViews
    txtTitle.setText(mTitle[position]);
    txtSubTitle.setText(mSubTitle[position]);

    return dropdownView;
}

public void filter(String text) {
    // TODO Auto-generated method stub

}

}

Populate.java

public class Populate 
{
private String Name;
private String Value;

public Populate(String Name, String Value) 
{
    this.Name = Name;
    this.Value = Value;
}

public String getName() 
{
    return this.Name;
}

public String getValue() 
{
    return this.Value;
}


}

SingleItemView.java

public class SingleItemView extends SherlockActivity
{
// Declare Variables
TextView txtName;
TextView txtValue;

String Name;
String Value;




@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.singleitemview);
    // Hide the keyboard
    InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

    // Retrieve data from **Numbers**.java on item click event
    Intent i = getIntent();
    // Get the results of Name
    Name = i.getStringExtra("Name");
    // Get the results of Value
    Value = i.getStringExtra("Value");


    // Locate the TextViews in singleitemview.xml
    txtName = (TextView) findViewById(R.id.Name);
    txtValue = (TextView) findViewById(R.id.Value);


    // Load the results into the TextViews
    txtName.setText(Name);
    txtValue.setText(Value);

}

}

FiveHunded.java&amp; OneThousand.java ---两个片段基本上都有相同的代码,但数据字符串表示不同的东西。

public class FiveHundred extends SherlockFragment
{
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] Name;
String[] Value;

ArrayList<Populate> arraylist = new ArrayList<Populate>();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 
{
     View rootView = inflater.inflate(R.layout.listview_main, container, false);
     return rootView;
}

@Override
public void onStart()
{
    super.onStart();

    // Generate sample data
    Name = new String[] 
            { 
                // 0-10
                "A name goes here!!" 
            };

    Value = new String[] 
            { 
                // 0-10
                "A value goes here!!"
            };


    // Locate the ListView in listview_main.xml
    list = (ListView) getView().findViewById(R.id.listview);

    for (int i = 0; i < Name.length; i++)
    {
        Populate p = new Populate(Name[i], Value[i]);
        // Binds all Strings into an array
        arraylist.add(p);
    }

    // Pass results to ListViewAdapter.class
    adapter = new ListViewAdapter(getActivity(), arraylist);

    // Binds the adapter to the ListView
    list.setAdapter(adapter);
}

}

1 个答案:

答案 0 :(得分:0)

我发现您的问题出在FiveHundedOneThousand类中。当ArrayList方法调用时,您不会清除OnStart,因此每次切换片段时都会向其添加数据,并且适配器会获得更大的ArrayList。

只需在初始化循环之前在arrayList.clear()方法中添加OnStart