简体   繁体   中英

listView items not clickable when I switched to Toolbar

I have a listview that loads in a fragment, is able to be scrolled, but I can not select any items in the listview.

The fragment code looks like this:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Mike on 2/16/14.
 */
public class BreweryStatistics extends Fragment implements GetBreweryStatisticsJSON.OnArticleSelectedListener {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.brewery_statistics_layout, container, false);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);

        String url = "myURL";


        //async task to get beer taste tag percents
        GetBreweryStatisticsJSON task = new GetBreweryStatisticsJSON(getActivity());
        task.setOnArticleSelectedListener(this);
        task.execute(url);


        // Inflate the layout for this fragment
        return v;

    }


    @Override
    public void onArticleSelected(String bID){

        //code to execute on click

        Fragment Fragment_one;
        FragmentManager man= getActivity().getSupportFragmentManager();
        FragmentTransaction tran = man.beginTransaction();
        Fragment_one = new BreweryTabs();
        //todo: add id
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("breweryID",bID);
        editor.commit();


        tran.replace(R.id.main, Fragment_one);//tran.
        tran.addToBackStack(null);
        tran.commit();

    }


}

The XML for the fragment is:

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


    <ListView
        android:id="@+id/yourBreweryStatistics"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:dividerHeight="0px"
        android:divider="@null"
        >
    </ListView>


</LinearLayout>

The ASyncTask looks like this:

public class GetBreweryStatisticsJSON extends AsyncTask<String, Void, String> {

    Context c;
    private ProgressDialog Dialog;


    public GetBreweryStatisticsJSON(Context context)
    {
        c = context;
        Dialog = new ProgressDialog(c);
    }

    //***************************code for on click
    OnArticleSelectedListener listener;
    public interface OnArticleSelectedListener{
        public void onArticleSelected(String myString);


    }
    public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
        this.listener = listener;


    }
    //*****************************end code for onClick

    protected void onPreExecute() {
        Dialog.setMessage("Analyzing breweries");

        Dialog.setTitle("Loading");
        Dialog.show();
    }


    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        return readJSONFeed(arg0[0]);
    }

    protected void onPostExecute(String result){
        //decode json here
        try{
            JSONArray jsonArray = new JSONArray(result);


            //acces listview
            ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourBreweryStatistics);

            //make array list for beer
            final List<BreweryInfo> tasteList = new ArrayList<BreweryInfo>();



            for(int i = 0; i < jsonArray.length(); i++) {

                String brewery = jsonArray.getJSONObject(i).getString("brewery");
                String rate = jsonArray.getJSONObject(i).getString("rate");
                String breweryID = jsonArray.getJSONObject(i).getString("id");

                int count = i + 1;

                brewery = count + ". " + brewery;

                Log.d("brewery stats", brewery);

                //create object
                BreweryInfo tempTaste = new BreweryInfo(brewery, breweryID, rate);

                //add to arraylist
                tasteList.add(tempTaste);


                //add items to listview
                BreweryInfoAdapter adapter1 = new BreweryInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
                lv.setAdapter(adapter1);

                //set up clicks
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        BreweryInfo o=(BreweryInfo)arg0.getItemAtPosition(arg2);

                        String bID = o.breweryID;

                        //todo: split up name
                        String [] arr = o.brewery.split(" ", 2);

                        String nameFinal = arr[1];

                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c);
                        SharedPreferences.Editor editor = preferences.edit();

                        editor.putString("breweryName",nameFinal);
                        editor.commit();


                        //********************* add listener
                        listener.onArticleSelected(bID);


                    }
                });

            }

        }
        catch(Exception e){

        }

        Dialog.dismiss();

    }

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }



}

If you are using layouts inside a listview, the child layouts will consume the on click event. Add this to the 'R.layout.brewer_stats_listview' layout's first element.

android:descendantFocusability="blocksDescendants"

Note: This will block any child element to receive the onclick event.

This was answered originally answered here : https://stackoverflow.com/a/13415566/4635282

It seems you are a victim of lack of documentation. Try this on your layout with the ListView:

android:focusable="false"
android:focusableInTouchMode="false"

I assume you don't need to have the list item focused when a user clicks on it. A good link I have read is at Stackoverflow - ListView OnItemClickListener Not Responding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM