在recyclelerview中清楚android edittext值

时间:2018-02-22 14:37:40

标签: android android-recyclerview

我正在开发一个包含片段和标签布局的应用。在我的细节片段中有两个标签。这是"类别"和"项目"。在项目显示列表中。我使用Recyclerview显示列表。我想在我在下面显示的列表中添加搜索。 serch工作正常。在列表中我想使用编辑文本。点击"保存"选项选项菜单我想要输入编辑文本recyclerview的值。 我的问题是输入时钟的值(在edittext中)。当搜索表风扇并回到所有项目时,编辑文本变得清晰。我希望价值是修复。当搜索另一个项目时。

Tab xml代码的片段

fragment_itemtab.xml

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

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <SearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"

        android:layout_height="wrap_content"
        android:queryHint="Search... " />

    <LinearLayout
    android:id="@+id/lItemsHeader"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="5dip"
    android:layout_marginRight="5dip"
    android:layout_marginTop="2dip"
    android:background="@color/title_background">


    <TextView
        android:id="@+id/item2"
        style="@style/ItemsHeader"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginLeft="3dip"
        android:layout_weight="40"
        android:width="0dip"
        android:text="@string/caption_item"
        android:textColor="@color/font1" />


    <TextView
        android:id="@+id/item4"
        style="@style/ItemsHeader"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="10"
        android:width="0dip"
        android:gravity="center_horizontal"
        android:text="Rate"
        android:textColor="@color/font1" />

    <TextView
        android:id="@+id/item5"
        style="@style/ItemsHeader"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="10"
        android:width="0dip"
        android:gravity="right"
        android:text="Qty"
        android:textColor="@color/font1" />

</LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical" />

</LinearLayout>

</RelativeLayout> 


The xml code of recyclerview

recyclerviewitem_item_tab.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="@color/recycler_item_background"
android:paddingBottom="5dp"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:orientation="vertical"
    android:padding="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:weightSum="1.0">

        <TextView

            android:id="@+id/Itemname"
            android:layout_width="90dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/Rate"
            android:layout_width="45dp"
            android:layout_height="match_parent"
            android:layout_weight="0.5"
            android:gravity="right" />

        <EditText
            android:id="@+id/Qty"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.3"
            android:ems="10"
            android:inputType="textPersonName"

             />


    </LinearLayout>

</LinearLayout>

</RelativeLayout>

Itemtab.java

public class Itemtab extends Fragment implements SearchView.OnQueryTextListener {

private RecyclerView mRecyclerView;
//private RecyclerView.Adapter mAdapter;
private RecyclerView.Adapter mAdapter = new Recycleradapter_item_tab(getDataSet());
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
private Recycleradapter_item_tab adapter;
String qty;
// AutoCompleteTextView pview;
private SearchView mSearchView;
View v;

private ArrayList<Item_object> results;
ViewPager viewPager;
public Itemtab() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   v = inflater.inflate(R.layout.fragment_itemtab, container, false);

    mSearchView = v.findViewById(R.id.search_view);
    viewPager =  getActivity().findViewById(R.id.pager);


    mRecyclerView = v.findViewById(R.id.my_recycler_view);


    setHasOptionsMenu(true);



    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new Recycleradapter_item_tab(getDataSet());
    mRecyclerView.setAdapter(mAdapter);
    RecyclerView.ItemDecoration itemDecoration =
            new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
    mRecyclerView.addItemDecoration(itemDecoration);


    adapter = new Recycleradapter_item_tab(this.getContext(),results );
    mRecyclerView.setAdapter(adapter);
    setupSearchView();
    return v;

}

private ArrayList<Item_object> getDataSet() {

    results = new ArrayList<Item_object>();
    Item_object obj;
int nl=0;
    //  adapter.notifyDataSetChanged();
    if(qty==null)
    {

        obj = new Item_object("Mobile phone", "20000");
        results.add(obj);
        obj = new Item_object("Table Fan", "2000");
        results.add(obj);
        obj = new Item_object("Bag", "1400");
        results.add(obj);
        obj = new Item_object("Clock", "500");
        results.add(obj);
    }
   else {
       nl=1;
      obj = new Item_object("Mobile phone", "20000", qty);
        results.add(obj);
        obj = new Item_object("Table Fan", "2000", qty);
        results.add(obj);
        obj = new Item_object("Bag", "1400", qty);
        results.add(obj);
        obj = new Item_object("Clock", "500", qty);
        results.add(obj);
    }

    Log.d("qty"+qty,"val");
  //  Toast.makeText(getActivity(), "qty "+nl , Toast.LENGTH_SHORT).show();
    return results;
}
private void setupSearchView() {

   // results.clone();

    mSearchView.setIconifiedByDefault(false);
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setSubmitButtonEnabled(true);
    // mSearchView.setQueryHint("Search Here");
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.home1, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.back:
            FragmentActivitiesInvoice fragmentActivitiesInvoice = new FragmentActivitiesInvoice();
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.content_frame, fragmentActivitiesInvoice);
            transaction.addToBackStack("tag");
            transaction.commit();
            //do something
            return true;

    }
    return super.onOptionsItemSelected(item);
}


@Override
public boolean onQueryTextSubmit(String query) {
    qty="3";
    Toast.makeText(getActivity(), "qty "+qty , Toast.LENGTH_SHORT).show();





    results.clone();
    adapter.notifyDataSetChanged();
    mAdapter.notifyDataSetChanged();

 return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    qty="3";
    Toast.makeText(getActivity(), "qty "+qty , Toast.LENGTH_SHORT).show();
    adapter.filter(newText);
    // mAdapter.filter(newText);
    results.clone();
mAdapter.notifyDataSetChanged();

adapter.notifyDataSetChanged();

    return false;
}
}

Recycleradapter_item_tab.java

public class Recycleradapter_item_tab  extends RecyclerView.Adapter <Recycleradapter_item_tab.DataObjectHolder>{
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<Item_object> mDataset,filterList;;
private static MyClickListener01 myClickListener;
private Context mContext;

private View.OnClickListener mListener;

public interface OnItemClickListener {
    public void onItemClick(View view, int position);

}

public interface ItemClickListener {
    void onClick(View view, int position, boolean isLongClick);
}




public ArrayList<Item_object> getmDataset() {
    return mDataset;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView itemname,rate,qty;
    TabLayout tabLayout;

    private ItemClickListener clickListener;



    public DataObjectHolder(View itemView) {
        super(itemView);

        rate = (TextView) itemView.findViewById(R.id.Rate);
        itemname = (TextView) itemView.findViewById(R.id.Itemname);
        qty = (TextView) itemView.findViewById(R.id.Qty);

        itemView.setOnClickListener(this);

        // Log.i(LOG_TAG, "Adding Listener");
        // itemView.setOnClickListener(this);
    }

    public void setClickListener(ItemClickListener itemClickListener) {
        this.clickListener = itemClickListener;
    }

    @Override
    public void onClick(View v) {
        // myClickListener.onItemClick(getPosition(), v);


       // tabLayout.getTabAt(1).select();


    }
}

public Recycleradapter_item_tab(Context contexts, ArrayList<Item_object> myDataset) {
    this.mContext = contexts;
    this.mDataset = myDataset;
    this.filterList = new ArrayList<Item_object>();
    // we copy the original list to the filter list and use it for setting row values
    this.filterList.addAll(this.mDataset);
}
public Recycleradapter_item_tab(ArrayList<Item_object> myDataset) {
    mDataset = myDataset;
}



@Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
                                           int viewType) {
    TextView name;

    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.recyclerviewitem_item_tab, parent, false);
    //  name= view.findViewById(R.id.itemname);
  /*  name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    /*TabHost host = v.findViewById(R.id.tabLayout);
    host.setCurrentTab(1);
    host.setup();*/
   /* View viewPager = v.findViewById(R.id.pager);
    viewPager.setCurrentItem(1);
   /*Pager2 mPager = null;
    mPager.setCurrentItem(1);
    */
    //     }
    // });


    DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
    return dataObjectHolder;


}

@Override
public void onBindViewHolder(final DataObjectHolder holder, int position) {

    //Item_object  = filterList.get(position);


    holder.itemname.setText(mDataset.get(position).getItemname());

    holder.qty.setText(mDataset.get(position).getQty());
    holder.rate.setText(mDataset.get(position).getRate());
    // Item_object itemlist=filterList.get(position);

    Item_object listItem = filterList.get(position);
    holder.itemname.setText(listItem.getItemname());
    // customViewHolder.tvName.setText(listItem.name);
    holder.setClickListener(new ItemClickListener() {
        @Override
        public void onClick(View view, int position, boolean isLongClick) {

        }
    });

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Log.d("LOG","clicked1:"+holder.itemname.getText().toString());


            popUp(holder.itemView.getContext(), holder.itemname.getText().toString(),holder.qty.getText().toString(),holder.rate.getText().toString());
        }
    });








}
@Override
public int getItemCount() {
    return (null != filterList ? filterList.size() : 0);
}


private void popUp(final Context context, final String name, final String qty, final String rate) {

    Button closePopupBtn,btnSubmit;
    Spinner spinner1, spinner2;
    final PopupWindow popupWindow;
    LayoutInflater layoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View customView = layoutInflater.inflate(R.layout.add_item_popup,null);
    closePopupBtn = (Button) customView.findViewById(R.id.closePopupBtn);
    spinner1 = (Spinner) customView.findViewById(R.id.spinner1);
    spinner2 = (Spinner) customView.findViewById(R.id.spinner2);
    ArrayList<String> item = new ArrayList<String>();
    item.add("Package of 100");
    item.add("Package of 10");
    item.add("Batch of 100");
    item.add("Batch of 10");

    ArrayList<String> item1 = new ArrayList<String>();
    item1.add("Package of 100");
    item1.add("Package of 10");
    item1.add("Batch of 100");
    item1.add("Batch of 10");


    ArrayAdapter <CharSequence> adapter = new ArrayAdapter(context,R.layout.spinner_item,item);
    adapter.setDropDownViewResource(R.layout.spinner_item);
    spinner1.setAdapter(adapter);

    ArrayAdapter <CharSequence> adapter1 = new ArrayAdapter(context,R.layout.spinner_item,item);
    adapter.setDropDownViewResource(R.layout.spinner_item);
    spinner2.setAdapter(adapter1);

    btnSubmit = customView.findViewById(R.id.btnSubmit);





    popupWindow = new PopupWindow(customView, 700, ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.showAtLocation(popupWindow.getContentView(), Gravity.CENTER, 0, 0);
    popupWindow.setOutsideTouchable(false);
    popupWindow.setFocusable(true);
    popupWindow.update();

    closePopupBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            popupWindow.dismiss();
        }
    });

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           /* Toast.makeText(mContext,"Successfully updated", Toast.LENGTH_SHORT).show();
            popupWindow.dismiss();*/
            String PREFS_NAME = "IVS_ITEM";
            String ITEMS = "items";

            SharedPreferences settings;
            SharedPreferences.Editor editor;
            settings = context.getSharedPreferences(PREFS_NAME,
                    Context.MODE_PRIVATE);
            editor = settings.edit();
            Gson gson = new Gson();

            if (settings.contains("items")) {
                Log.d("LOG","having shared ");
                String jsonItems = settings.getString("items", null);
                List<Cash> products;

                Cash[] pItems = gson.fromJson(jsonItems,
                        Cash[].class);

                products = Arrays.asList(pItems);
                products = new ArrayList<Cash>(products);
                Cash cash = new Cash(qty,qty,rate,name);products.add(cash);


                String jsonProducts = gson.toJson(products);
                editor.putString(ITEMS, jsonProducts);
                editor.commit();


            }else {

                List<Cash> products;
                products = new ArrayList<Cash>();



                Cash cash = new Cash(qty,qty,rate,name);products.add(cash);

                String jsonProducts = gson.toJson(products);
                editor.putString(ITEMS, jsonProducts);
                editor.commit();


                Log.d("LOG","no shared ");
            }





                /*
                String jsonItems = settings.getString("Items", null);
                Gson gson = new Gson();
                List<Class> mListItems = new ArrayList<Class>();
                settings = context.getSharedPreferences("Items",
                        Context.MODE_PRIVATE);
                Class[] items = gson.fromJson(jsonItems,
                        Class[].class);

                mListItems = Arrays.asList(items);
                mListItems = new ArrayList<Class>(mListItems);
                Log.d("LOG", "Refund : " + mListItems.size());

                */





          /*  SharedPreferences settings;

            SharedPreferences.Editor editor = null;

            List<Class> mListItems = new ArrayList<Class>();
            settings = context.getSharedPreferences("Items",
                    Context.MODE_PRIVATE);

            if (settings.contains("Items")) {
                String jsonItems = settings.getString("Refund", null);
                Gson gson = new Gson();
                Class[] items = gson.fromJson(jsonItems,
                        Class[].class);

                mListItems = Arrays.asList(items);
                mListItems = new ArrayList<Class>(mListItems);
                Log.d("LOG", "Refund : " + mListItems.size());

                ArrayList<HashMap<String, String>> list;

                list = new ArrayList<HashMap<String, String>>();


            }*/

            Toast.makeText(context,"Successfully updated", Toast.LENGTH_SHORT).show();
            popupWindow.dismiss();


        }
    });


}


public void addItem(Item_object dataObj, int index) {
    mDataset.add(dataObj);
    notifyItemInserted(index);
}

public void deleteItem(int index) {
    mDataset.remove(index);
    notifyItemRemoved(index);
}




private static class MyClickListener01 {

}

public void setClickListener(View.OnClickListener callback) {
    mListener = callback;
}
public void filter(final String text) {

    // Searching could be complex..so we will dispatch it to a different thread...
    new Thread(new Runnable() {
        @Override
        public void run() {

            // Clear the filter list
            filterList.clear();

            // If there is no search value, then add all original list items to filter list
            if (TextUtils.isEmpty(text)) {

                filterList.addAll( mDataset);

            } else {
                // Iterate in the original List and add it to filter list...
                for (Item_object item :  mDataset) {
                    if (item.itemname.toLowerCase().contains(text.toLowerCase()) ) {
                        // Adding Matched items
                        filterList.add(item);
                    }
                }
            }

            // Set on UI Thread
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Notify the List that the DataSet has changed...
                    notifyDataSetChanged();
                }
            });

        }
    }).start();

}

}

Itemtab.java

public class Itemtab extends Fragment implements SearchView.OnQueryTextListener {
private RecyclerView mRecyclerView;
//private RecyclerView.Adapter mAdapter;
private RecyclerView.Adapter mAdapter = new Recycleradapter_item_tab(getDataSet());
private RecyclerView.LayoutManager mLayoutManager;
private static String LOG_TAG = "RecyclerViewActivity";
private Recycleradapter_item_tab adapter;
String qty;
// AutoCompleteTextView pview;
private SearchView mSearchView;
View v;

private ArrayList<Item_object> results;
ViewPager viewPager;
public Itemtab() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
   v = inflater.inflate(R.layout.fragment_itemtab, container, false);

    mSearchView = v.findViewById(R.id.search_view);
    viewPager =  getActivity().findViewById(R.id.pager);


    mRecyclerView = v.findViewById(R.id.my_recycler_view);


    setHasOptionsMenu(true);



    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getContext());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new Recycleradapter_item_tab(getDataSet());
    mRecyclerView.setAdapter(mAdapter);
    RecyclerView.ItemDecoration itemDecoration =
            new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
    mRecyclerView.addItemDecoration(itemDecoration);


    adapter = new Recycleradapter_item_tab(this.getContext(),results );
    mRecyclerView.setAdapter(adapter);
    setupSearchView();
    return v;

}

private ArrayList<Item_object> getDataSet() {

    results = new ArrayList<Item_object>();
    Item_object obj;
int nl=0;
    //  adapter.notifyDataSetChanged();
    if(qty==null)
    {

        obj = new Item_object("Mobile phone", "20000");
        results.add(obj);
        obj = new Item_object("Table Fan", "2000");
        results.add(obj);
        obj = new Item_object("Bag", "1400");
        results.add(obj);
        obj = new Item_object("Clock", "500");
        results.add(obj);
    }
   else {
       nl=1;
      obj = new Item_object("Mobile phone", "20000", qty);
        results.add(obj);
        obj = new Item_object("Table Fan", "2000", qty);
        results.add(obj);
        obj = new Item_object("Bag", "1400", qty);
        results.add(obj);
        obj = new Item_object("Clock", "500", qty);
        results.add(obj);
    }

    Log.d("qty"+qty,"val");
  //  Toast.makeText(getActivity(), "qty "+nl , Toast.LENGTH_SHORT).show();
    return results;
}
private void setupSearchView() {

   // results.clone();

    mSearchView.setIconifiedByDefault(false);
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setSubmitButtonEnabled(true);
    // mSearchView.setQueryHint("Search Here");
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.home1, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.back:
            FragmentActivitiesInvoice fragmentActivitiesInvoice = new FragmentActivitiesInvoice();
            FragmentManager manager = getFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            transaction.replace(R.id.content_frame, fragmentActivitiesInvoice);
            transaction.addToBackStack("tag");
            transaction.commit();
            //do something
            return true;

    }
    return super.onOptionsItemSelected(item);
}


@Override
public boolean onQueryTextSubmit(String query) {






    results.clone();
    adapter.notifyDataSetChanged();
    mAdapter.notifyDataSetChanged();

 return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    qty="3";
    Toast.makeText(getActivity(), "qty "+qty , Toast.LENGTH_SHORT).show();
    adapter.filter(newText);
    // mAdapter.filter(newText);
    results.clone();
mAdapter.notifyDataSetChanged();
adapter.notifyDataSetChanged();

    return false;
}
}

enter image description here

enter image description here

第一张图片在edittext中输入数字。第二张图片正在清理。怎么解决?请帮帮我?

1 个答案:

答案 0 :(得分:1)

首先在Item_object中创建一个字段当前值为 -

int currentValue;

currentValue中的每个editText设置onBindViewHolder(),如果currentValue =,则可以将editText留空  0
现在为recycler视图中的每个editText实现TextWatcher 基于currentValue

的文字更改更新position

现在,如果你进行过滤,你会看到你的价值保留在edittext的给定位置项

对于textwatcher,请参阅链接 - How to use the TextWatcher class in Android?