当我切换到工具栏时,listView项目无法点击

时间:2015-03-05 04:36:09

标签: android listview android-fragments android-listview

我有一个列表视图加载片段,可以滚动,但我无法选择列表视图中的任何项目。

片段代码如下所示:

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();

    }


}

片段的XML是:

<?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>

ASyncTask看起来像这样:

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();
    }



}

2 个答案:

答案 0 :(得分:2)

如果您在列表视图中使用布局,则子布局将使用on click事件。将其添加到&#39; R.layout.brewer_stats_listview&#39;布局的第一个元素。

android:descendantFocusability="blocksDescendants"

注意:这将阻止任何子元素接收onclick事件。

最初在这里回答的答案是:https://stackoverflow.com/a/13415566/4635282

答案 1 :(得分:0)

您似乎是缺乏文档的受害者。使用ListView在您的布局上尝试这个:

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

我假设您不需要在用户点击它时关注列表项。 我读过的一个很好的链接是Stackoverflow - ListView OnItemClickListener Not Responding