2014-11-05 3 views
1

Я пытаюсь сделать поиск в списке для своего приложения. Я нашел много учебников, которые делают именно это, когда панель поиска помещается наверху, и если вы введете поле, результаты будут отфильтрованы.Поиск элементов ListView на Android, всегда открывающий первый элемент ListView

Но когда я нажимаю на найденный элемент, он открывает первый элемент ListView, а не поиск. Поиск выполняется успешно, но при нажатии на отфильтрованные результаты он всегда отображает первый элемент списка. И когда список не находится в режиме фильтрации, он работает нормально.

В моем приложении я хочу щелкнуть по заданным элементам после завершения фильтрации, я внедрил setOnItemClickListener.

Пожалуйста, помогите ...!

УСЛЫШАТЬ в мой код:

Фрагмент A, в которой я реализовал ListView.

public class FragmentAwarenessA extends Fragment implements 
     OnItemClickListener, SearchView.OnQueryTextListener { 

    ListView list; 
    Communicator communicator; 
    SearchView searchview; 



    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     View view = inflater.inflate(R.layout.fragment_awareness_a, container, 
       false); 
     list = (ListView) view.findViewById(R.id.listView1); 
     searchview = (SearchView) view.findViewById(R.id.etSearch); 
     ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), 
       R.array.diseases, android.R.layout.simple_list_item_1); 
     list.setAdapter(adapter); 
     list.setOnItemClickListener(this); 
     list.setTextFilterEnabled(true); 

     searchview.setOnQueryTextListener(this); 

     return view; 
    } 

    public void setCommunicator(Communicator communicator) { 
     this.communicator = communicator; 
    } 

    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, 
      long id) { 
     // TODO Auto-generated method stub 

     communicator.respond(position); 
     // communicator.click(); 

    } 

    public interface Communicator { 

     public void respond(int index); 

     // public void click(); 
    } 

    @Override 
    public boolean onQueryTextSubmit(String query) { 
     // TODO Auto-generated method stub 
     return false; 
    } 

    @Override 
    public boolean onQueryTextChange(String newText) { 
     // TODO Auto-generated method stub 
     if (TextUtils.isEmpty(newText)) { 
      // clear text filter so that list displays all items 
      list.clearTextFilter(); 

     } else { 
      // apply filter so that list displays only 
      // matching child items 
      list.setFilterText(newText.toString()); 

     } 
     return true; 

    } 

} 

Это мой фрагмент B, который отображается, когда пользователь нажимает на элемент списка.

public class FragmentAwarenessB extends Fragment { 

    TextView text, textS, textC, textT, textDescHeading, textSymHeading, 
      textCausesHeading, textTreatHeading; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     View view = inflater.inflate(R.layout.fragment_awareness_b, container, 
       false); 
     text = (TextView) view.findViewById(R.id.tvDescriptionData); 
     textS = (TextView) view.findViewById(R.id.tvSymptomsData); 
     textC = (TextView) view.findViewById(R.id.tvCausesData); 
     textT = (TextView) view.findViewById(R.id.tvTreatmentData); 
     textDescHeading = (TextView) view.findViewById(R.id.tvDescription); 
     textSymHeading = (TextView) view.findViewById(R.id.tvSymptoms); 
     textCausesHeading = (TextView) view.findViewById(R.id.tvCauses); 
     textTreatHeading = (TextView) view.findViewById(R.id.tvTreatment); 
     return view; 
    } 

    public void ChangeData(int index) { 
     String[] descriptions = getResources().getStringArray(
       R.array.description); 
     text.setText(descriptions[index]); 

     String[] symptoms = getResources().getStringArray(R.array.symptoms); 
     textS.setText(symptoms[index]); 

     String[] causes = getResources().getStringArray(R.array.causes); 
     textC.setText(causes[index]); 

     String[] treatment = getResources().getStringArray(R.array.treatment); 
     textT.setText(treatment[index]); 

     String[] dheadings = getResources().getStringArray(R.array.Dheadings); 
     textDescHeading.setText(dheadings[index]); 

     String[] sheadings = getResources().getStringArray(R.array.Sheadings); 
     textSymHeading.setText(sheadings[index]); 

     String[] cheadings = getResources().getStringArray(R.array.Cheadings); 
     textCausesHeading.setText(cheadings[index]); 

     String[] theadings = getResources().getStringArray(R.array.Theadings); 
     textTreatHeading.setText(theadings[index]); 

    } 

} 

Вот мой MainActivity, который выступает в качестве коммуникационного канала между двумя фрагментами:

public class FriendsActivity extends Activity implements 
     FragmentAwarenessA.Communicator { 

    FragmentAwarenessA f1; 
    FragmentAwarenessB f2; 
    FragmentManager manager; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_awareness); 

     manager = getFragmentManager(); 
     f1 = (FragmentAwarenessA) manager.findFragmentById(R.id.fragment1); 
     f1.setCommunicator(this); 
    } 

    @Override 
    public void respond(int index) { 
     // TODO Auto-generated method stub 
     f2 = (FragmentAwarenessB) manager.findFragmentById(R.id.fragment2); 
     if (f2 != null && f2.isVisible()) { 

      f2.ChangeData(index); 

     } else { 

      Intent intent = new Intent(this, AwarenessActivityLand.class); 
      intent.putExtra("index", index); 
      startActivity(intent); 

     } 
    } 

} 

И, наконец, strings.xml файл, содержащий все массивы:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 

    <string name="hello">Hello World, AndroidDashboardDesignActivity!</string> 
    <string name="app_name">Health Care</string> 

    <string-array name="diseases"> 
     <item>Anxiety disorder</item> 
     <item>Asthma</item> 
     <item>Cellulitis (skin infection)</item> 
     <item>Depression (excessive sadness)</item> 
     <item>Diabetes (high blood sugar)</item> 
     <item>High cholesterol (hypercholesteremia)</item> 
     <item>Hypertension (high blood pressure)</item> 
     <item>Influenza (seasonal flu)</item> 
     <item>Kidney stone (nephrolithiasis)</item> 
     <item>Obesity</item> 
     <item>Sinusitis (sinus infection)</item> 
    </string-array> 
    <string-array name="Dheadings"> 
     <item>Description of Anxiety disorder</item> 
     <item>Description of Asthma</item> 
     <item>Description of Cellulitis (skin infection)</item> 
     <item>Description of Depression (excessive sadness)</item> 
     <item>Description of Diabetes (high blood sugar)</item> 
     <item>Description of High cholesterol (hypercholesteremia)</item> 
     <item>Description of Hypertension (high blood pressure)</item> 
     <item>Description of Influenza (seasonal flu)</item> 
     <item>Description of Kidney stone (nephrolithiasis)</item> 
     <item>Description of Obesity</item> 
     <item>Description of Sinusitis (sinus infection)</item> 
    </string-array> 
    <string-array name="Sheadings"> 
     <item>Symptoms of Anxiety disorder</item> 
     <item>Symptoms of Asthma</item> 
     <item>Symptoms of Cellulitis (skin infection)</item> 
     <item>Symptoms of Depression (excessive sadness)</item> 
     <item>Symptoms of Diabetes (high blood sugar)</item> 
     <item>Symptoms of High cholesterol (hypercholesteremia)</item> 
     <item>Symptoms of Hypertension (high blood pressure)</item> 
     <item>Symptoms of Influenza (seasonal flu)</item> 
     <item>Symptoms of Kidney stone (nephrolithiasis)</item> 
     <item>Symptoms of Obesity</item> 
     <item>Symptoms of Sinusitis (sinus infection)</item> 
    </string-array> 
    <string-array name="Cheadings"> 
     <item>Causes of Anxiety disorder</item> 
     <item>Causes of Asthma</item> 
     <item>Causes of Cellulitis (skin infection)</item> 
     <item>Causes of Depression (excessive sadness)</item> 
     <item>Causes of Diabetes (high blood sugar)</item> 
     <item>Causes of High cholesterol (hypercholesteremia)</item> 
     <item>Causes of Hypertension (high blood pressure)</item> 
     <item>Causes of Influenza (seasonal flu)</item> 
     <item>Causes of Kidney stone (nephrolithiasis)</item> 
     <item>Causes of Obesity</item> 
     <item>Causes of Sinusitis (sinus infection)</item> 
    </string-array> 
    <string-array name="Theadings"> 
     <item>Treatment of Anxiety disorder</item> 
     <item>Treatment of Asthma</item> 
     <item>Treatment of Cellulitis (skin infection)</item> 
     <item>Treatment of Depression (excessive sadness)</item> 
     <item>Treatment of Diabetes (high blood sugar)</item> 
     <item>Treatment of High cholesterol (hypercholesteremia)</item> 
     <item>Treatment of Hypertension (high blood pressure)</item> 
     <item>Treatment of Influenza (seasonal flu)</item> 
     <item>Treatment of Kidney stone (nephrolithiasis)</item> 
     <item>Treatment of Obesity</item> 
     <item>Treatment of Sinusitis (sinus infection)</item> 
    </string-array> 
    <string-array name="description"> 
     <item>A psychological disorder in which anxiety is so severe they prevent a person from performing their normal daily activities.</item> 
     <item>An inflammatory disease of the lungs characterized by reversible airway obstruction.</item> 
     <item>A skin infection usually caused by bacteria. Bacteria can enter into the skin either through a cut or insect bite and spread to deeper tissues causing an infection.</item> 
     <item>A mental state or chronic psychiatric disorder characterized by excessive feelings of sadness, loneliness, despair, helplessness, low self-esteem, and self-reproach. Depression is different than normal sadness because it prevents the person from functioning normally in their daily life.</item> 
     <item>A chronic disease of metabolism distinguished by the body\'s inability to produce enough insulin, and/or a resistance to the insulin being made. There are three types of diabetes: Type 1 is usually found in younger patients and requires insulin, Type 2 develops later in life and is more commonly associated with obesity.</item> 
     <item>Elevated levels of cholesterol in the blood increases the risk of having narrowed arteries. The blockage is caused by a buildup of plaque and fat deposits (atherosclerosis).</item> 
     <item>A termed used for high blood pressure. There are two numbers with the first number representing the systolic pressure (normal less than 140) and the second number the diastolic (normal if less than 90). Hypertension usually causes no symptoms but is a major risk factor for a number of serious long term problems including heart attacks, stroke and kidney failure.</item> 
     <item>A common, viral respiratory infection. It is contagious with an incubation period of 24 to 48 hours after exposure.</item> 
     <item>Kidney stones are small, solid particles that form in one or both kidneys. The majority of kidney stones contain calcium oxalate. Other types of stones contain uric acid, struvite, and cystine.</item> 
     <item>Defined as an increase in total body fat, or at least a 20% increase in one\'s ideal body weight.</item> 
     <item>Sinusitis is the inflammation or infection of the sinuses. The sinuses are cavities in the facial portion of the skull, and lined by mucosa.</item> 
    </string-array> 
    <string-array name="symptoms"> 
     <item>Fear, apprehension, muscle tension, restlessness, palpitations, rapid breathing, jitteriness, hyper vigilance, confusion, decreased concentration, fear of losing control.</item> 
     <item>Shortness of breath, wheezing, cough, low oxygen, fainting.</item> 
     <item>The affected skin becomes painful, red, warm to the touch, and swollen. If the surrounding lymph channels become infected red streaks up the arm or leg will be seen. These red streaks are called lymphangitis. Patients may also experience fever and fatigue.</item> 
     <item>Patients suffering from the following symptoms may have depression: excessive sadness, problems falling asleep, sleeping too much, problems concentrating, uncontrollable negative thoughts, no appetite, short temper, feeling helpless, increase in drinking alcohol, increase reckless behavior, increased fatigue, thoughts life isn\'t worth living.</item> 
     <item>Increased urination, increased drinking of fluids, increased appetite, nausea, fatigue, blurry vision, numbness or tingling in the feet.</item> 
     <item>There are usually no symptoms related to having elevated cholesterol.</item> 
     <item>Usually none. If the level is very high the following may be experienced: chest pain, headache, shortness of breath, confusion.</item> 
     <item>Fever, headache, tiredness (fatigue), chills, dry cough, sore throat, stuffy and congested nose, muscle aches and stiffness.</item> 
     <item>Flank, back and or abdominal pain; pain often radiates to the groin: abnormal urine color, blood in the urine; nausea, vomiting; painful urination; urinary frequency/urgency, urinary hesitancy.</item> 
     <item>Most of the symptoms of obesity come from the diseases obesity causes such as arthritis, heart disease, gallstones, sleep apnea, and poor self-esteem. These symptoms include: back pain, hip pain, knee pain, ankle pain, neck pain, chest pain, breathing problems, sadness, depression, snoring, rashes in the folds of the skin, and excessive sweating.</item> 
     <item>Pain in the face, cough, fatigue, fever, headache, pain behind the eyes, toothache, facial tenderness, nasal congestion and discharge, sore throat, postnasal drip.</item> 
    </string-array> 
    <string-array name="causes"> 
     <item>Stressful events can also trigger symptoms of anxiety. Common triggers include: job stress or job change, change in living arrangements, family and relationship problems, major emotional shock following a stressful or traumatic event, death or loss of a loved one.</item> 
     <item>No one quite understands what causes asthma, but research has shown that environmental allergens can cause asthma symptoms. These allergens are called “triggers” and include: Pollen, Pet dander, Viral upper respiratory infections, Acid reflux, Sulfites found in food and drinks, Cigarette smoke, Air pollution, Dust.</item> 
     <item>Cellulitis is usually caused by bacteria that enter the body through a break in the skin. The bacteria most commonly responsible for cellulitis are staphylococci (staph) and streptococci (strep).</item> 
     <item>Depression has many possible causes, including faulty mood regulation by the brain, genetic vulnerability, stressful life events, medications, and medical problems. It’s believed that several of these forces interact to bring on depression.</item> 
     <item>Diabetes are caused by problems with the pancreas, an organ in the abdomen. The pancreas is located behind and below the stomach and has cells within it called islet cells. When a person eats, these cells normally produce insulin, a hormone that converts the glucose (sugar) from food into energy.</item> 
     <item>High cholesterol comes from a variety of sources, including your family history and what you eat. Here are some factors: Your diet, Your weight, Your activity level, Your age and gender, Your overall health, Your family history and Cigarette smoking. </item> 
     <item>There are two types of hypertension: primary or essential hypertension, and secondary or identifiable hypertension. People are diagnosed with primary hypertension when there is no clear explanation for their high blood pressure. Secondary hypertension is caused by another medical condition, such as diabetes or kidney disease.</item> 
     <item>Influenza is caused by a family of viruses. The virus is usually transmitted through the air. When an infected person coughs, sneezes or talks, he or she can emit infected droplets. Flu viruses can also be spread by direct personal contact.</item> 
     <item>Kidney stones are caused by high levels of certain minerals in the urine such as calcium, oxalate and uric acid. Some foods may cause kidney stones in certain people.</item> 
     <item>There are many causes of obesity from genetic to environmental factors, and certain conditions including Cushing\'s syndrome, hypothyroidism and medications, such as steroids, can cause obesity. In the great majority of cases no secondary cause is determined.</item> 
     <item>Allergies and the common cold are the most frequent causes of sinus infection. Infected teeth, fungal infections, nasal polyps and a deviated septum can also cause a sinus infection, although these cases are less common.</item> 
    </string-array> 
    <string-array name="treatment"> 
     <item>Therapy depends on the severity of symptoms. Treatment may include: benzodiazepines (diazepam/Valium, lorazepam/Ativan), antidepressant medications, psychological counseling, and/or psychological treatment such as cognitive-behavioral therapy.</item> 
     <item>Asthma is a chronic (long term) condition that has no cure. Asthma treatment is designed to: Control symptoms, Lower the need for quick-relief medicines (like inhalers), Help you keep your lungs healthy and functioning normally, Help you maintain the ability to perform day-to-day activities, Help you get a good night’s sleep, Help you avoid asthma attacks that could lead to an emergency room visit.</item> 
     <item>Cleaning and bandaging of any lacerations or abrasions will be done. Removal of the stinger will be performed if the infection is from an insect bite.</item> 
     <item>Antidepressants and/or psychotherapy are the mainstays of treatment. Psychiatric hospitalizations may be needed for severe symptoms and for those with suicidal thoughts.</item> 
     <item>Type 1 diabetes requires supplemental insulin either as an injection or as an intermittent continuous infusion delivered from an insulin pump. The insulin doses required are dependent on glucose measurements performed during the day. Type 2 diabetes times can often be controlled with weight loss, dietary discretion and exercise.</item> 
     <item>Treatment depends on how high the LDL level is and if other risk factors for developing blockage of the arteries (atherosclerosis) are present. Eating healthy foods, exercising more, and losing weight can improve mild elevations of cholesterol.</item> 
     <item>Treatment includes salt restriction, loss of excess weight, exercise and, in many cases, medications to reduce the pressure.</item> 
     <item>Rest and medications to reverse the fever such as acetaminophen(Tylenol) and/or ibuprofen (Motrin, Advil) are administered to reduce the symptoms. Patients are encouraged to drink plenty of fluids.</item> 
     <item>Vigorous oral or intravenous fluids, pain medications and anti-nausea medications are the primary treatments. Most stones less than 6mm in size will pass on their own. Stones that don\'t pass on their own will need to be removed during a cystoscopy or other surgical procedure.</item> 
     <item>Treatment is aimed at decreasing the intake of calories while still maintaining a healthy diet, and increasing exercise.</item> 
     <item>Sinusitis from allergy is treated with antihistamines, nasal sprays, decongestants or allergy shots.</item> 
    </string-array> 

</resources> 

Пожалуйста, помогите .. ..

+0

коммуникатор.ответ (позиция), что такое метод «ответа»? Где это? –

+0

Он определен в интерфейсе в фрагменте A и реализован в MainActivity. – Asad

+0

@Override public void reply (int index) { // TODO Автоматически генерируемый метод заглушки f2 = (FragmentAwarenessB) manager.findFragmentById (R.id.fragment2); if (f2! = Null && f2.isVisible()) { f2.ChangeData (index); } else { Цель намерения = новое намерение (это, AwarenessActivityLand.class); intent.putExtra («индекс», индекс); startActivity (намерение); } – Asad

ответ

2

Это произошло потому, что после фильтрации в вашем списке было только один элемент, s o index равен 0. Если вы хотите получить позицию ожидаемых элементов, вы должны использовать элемент настраиваемого списка, который будет содержать позицию и значение.

Если вы не хотите использовать пользовательский элемент списка, вы можете добавить новый метод

private int getIndexByValue(String arrayValue){ 
    String[] diseases = getResources().getStringArray(R.array.diseases); 
    return java.util.Arrays.asList(diseases).indexOf(arrayValue); 
} 

и изменить ваш onItemClick так:

@Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, 
      long id) { 
     // TODO Auto-generated method stub 
     String selectedText = (String) parent.getItemAtPosition(position); 
     communicator.respond(getIndexByValue(selectedText)); 
     // communicator.click();  
    } 

Но это не очень хорошо решение, довольно временное) Но с минимальными изменениями. Надеюсь, поможет.

+0

Нет изменений, которые я мог бы внести в этот код для решения этой проблемы ... вместо создания пользовательского списка? – Asad

+0

Я обновил свой ответ. –

+0

Спасибо человеку !! Спасибо огромное ! Работает отлично ....! – Asad

Смежные вопросы