ListFragment setOnItemClickListener不起作用

时间:2014-12-18 07:21:50

标签: android android-fragments

处理片段并希望在Fragment中单击ListActvity时打开新活动。但是它显示列表并且可单击但不能打开。我已经采用了所有方法,请查看代码。

在以下行代码下,它没有打开新活动。   listview.setOnItemClickListener(新OnItemClickListener()无法实现新活动

 public class FragmentOne extends ListFragment {
    public boolean net;
    ImageView ivIcon;
    TextView tvItemName;
    final static String LOG_TAG = "rnc";
     ListView listview;

public FragmentOne() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.twit_list, container,
            false);

    //View view = inflater.inflate(R.layout.twit_list, container,false);
listview = (ListView) view.findViewById(android.R.id.list); 



    downloadTweets();


      listview.setOnItemClickListener(new OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view,
                       int position, long id) {   
             // selected item
             String lst_txt = parent.getItemAtPosition(position).toString().trim();

             System.out.println("Display text"+lst_txt ); 
             // Launching new Activity on selecting single List Item
             Intent i = new Intent(getActivity().getBaseContext(), SingleListItem.class);
             // sending data to new activity
             i.putExtra("product",lst_txt );
         startActivity(i);
             //getActivity().startActivity(i);
           }
        });







    return view;

}


public void downloadTweets() {
    TwitterUser o = new TwitterUser();
    String m = o.getValue();

     System.out.println("Kida   "+m);


//   listview = this.getListView();



     String ScreenName =m;

    ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        new DownloadTwitterTask().execute(ScreenName);
    } else {
        Log.v(LOG_TAG, "No network connection available.");
    }
}



// Uses an AsyncTask to download a Twitter user's timeline
    private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
        final static String CONSUMER_KEY = "gtrg5454g45g45g54g45g54g45U";
        final static String CONSUMER_SECRET = "s54g54g54g54g5g54v2HD5VX3RDYefekCoDG";
        final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
        final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";


        private ProgressDialog progressDialog;  
        @Override
        // can use UI thread here
        protected void onPreExecute() {
        //this.progressDialog = ProgressDialog.show(Boys.this, ""," Look whose back !! Ok Let me see what i have for you ");  
            try{
            progressDialog = new ProgressDialog(FragmentOne.this.getActivity(),AlertDialog.THEME_HOLO_DARK);
            progressDialog.setIndeterminate(true);
            progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.loader_2));
            progressDialog.setMessage("Please Wait ! Unwrapping Something for You...");
            progressDialog.show();
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            }
            catch(Exception e)
            {
                this.progressDialog.dismiss();
                Toast.makeText(getActivity().getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();

            }
        }

        @Override
        protected String doInBackground(String... screenNames) {
            String result = null;

            if (screenNames.length > 0) {
                result = getTwitterStream(screenNames[0]);
            }
            return result;
        }

        // onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
        @Override
        protected void onPostExecute(String result) {
            Twitter twits = jsonToTwitter(result);

            // lets write the results to the console as well
            for (Tweet tweet : twits) {
                Log.i(LOG_TAG, tweet.getText());
            }

            System.out.println("Kamina "+ twits);

            // send the tweets to the adapter for rendering

                ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(getActivity().getBaseContext(),R.layout.customgrid,R.id.texts, twits);
                setListAdapter(adapter);


            this.progressDialog.dismiss();
        }

        // converts a string of JSON data into a Twitter object
        private Twitter jsonToTwitter(String result) {
            Twitter twits = null;
            if (result != null && result.length() > 0) {
                try {
                    Gson gson = new Gson();
                    twits = gson.fromJson(result, Twitter.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return twits;
        }

        // convert a JSON authentication object into an Authenticated object
        private Authenticated jsonToAuthenticated(String rawAuthorization) {
            Authenticated auth = null;
            if (rawAuthorization != null && rawAuthorization.length() > 0) {
                try {
                    Gson gson = new Gson();
                    auth = gson.fromJson(rawAuthorization, Authenticated.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return auth;
        }

        private String getResponseBody(HttpRequestBase request) {
            StringBuilder sb = new StringBuilder();
            try {

                DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();

                if (statusCode == 200) {

                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();

                    BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sb.append(line);
                    }
                } else {
                    sb.append(reason);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (ClientProtocolException ex1) {
            } catch (IOException ex2) {
            }
            return sb.toString();
        }

        private String getTwitterStream(String screenName) {
            String results = null;

            // Step 1: Encode consumer key and secret
            try {
                // URL encode the consumer key and secret
                String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
                String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

                // Concatenate the encoded consumer key, a colon character, and the
                // encoded consumer secret
                String combined = urlApiKey + ":" + urlApiSecret;

                // Base64 encode the string
                String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

                // Step 2: Obtain a bearer token
                HttpPost httpPost = new HttpPost(TwitterTokenURL);
                httpPost.setHeader("Authorization", "Basic " + base64Encoded);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
                String rawAuthorization = getResponseBody(httpPost);
                Authenticated auth = jsonToAuthenticated(rawAuthorization);

                // Applications should verify that the value associated with the
                // token_type key of the returned object is bearer
                if (auth != null && auth.token_type.equals("bearer")) {

                    // Step 3: Authenticate API requests with bearer token
                    HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName+"&count=10");

                    // construct a normal HTTPS request and include an Authorization
                    // header with the value of Bearer <>
                    httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
                    httpGet.setHeader("Content-Type", "application/json");
                    // update the results with the body of the response
                    results = getResponseBody(httpGet);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (IllegalStateException ex1) {
            }
            return results;
        }
    }

}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
    android:background="@drawable/abc" 

        >

<ListView  
          android:id="@android:id/list"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">

</ListView>


</LinearLayout>

customgrid.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ImageView
                android:id="@+id/image_id"
                android:layout_width="52dp"
                android:layout_height="52dp"
                android:layout_gravity="left"
                android:src="@drawable/ico" /> 

<TextView 
    android:id="@+id/texts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:text="text"
    android:textStyle="bold"
/>

</LinearLayout>

1 个答案:

答案 0 :(得分:1)

在onCreate方法

之外定义它
 @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Log.i("FragmentList2", "Item clicked: " + id);
   //     item = ((String)getListAdapter().getItem(position));

        Object selectedValue = this.getListAdapter().getItem(position);
        product = selectedValue.toString();


        System.out.println("lota "+product);

        Intent intent = new Intent(FragmentOne.this.getActivity(), SingleListItem.class);
        intent.putExtra("product", product);
    //    Toast.makeText(getActivity(), item, Toast.LENGTH_LONG).show();
      startActivity(intent);
    }