Android ListFragment setOnItemClickListener不工作

Android ListFragment setOnItemClickListener不工作,android,android-fragments,Android,Android Fragments,正在处理片段,并希望在片段中存在单击ListActivity时打开新活动。但它显示列表并可单击,但不打开。我已经走了所有的方法,请看一下代码 在下面的代码行下,它没有打开新活动。 listview.setOnItemClickListener(新建OnItemClickListener()无法执行新活动 public class FragmentOne extends ListFragment { public boolean net; ImageView ivIcon;

正在处理片段,并希望在片段中存在单击ListActivity时打开新活动。但它显示列表并可单击,但不打开。我已经走了所有的方法,请看一下代码

在下面的代码行下,它没有打开新活动。 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;
        }
    }
公共类FragmentOne扩展了ListFragment{
公共布尔网;
ImageView-ivIcon;
文本视图TVTItemName;
最终静态字符串日志\u TAG=“rnc”;
列表视图列表视图;
公共碎片1(){
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图=充气机。充气(R.layout.twit_列表,容器,
假);
//视图=充气机。充气(R.layout.twit_列表,容器,错误);
listview=(listview)view.findviewbyd(android.R.id.list);
下载tweets();
setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
int位置,长id){
//选定项目
字符串lst_txt=parent.getItemAtPosition(position.toString().trim();
System.out.println(“显示文本”+lst_txt);
//在选择单个列表项时启动新活动
Intent i=新的Intent(getActivity().getBaseContext(),SingleListItem.class);
//向新活动发送数据
i、 putExtra(“产品”,lst_txt);
星触觉(i);
//getActivity().startActivity(i);
}
});
返回视图;
}
公共void下载tweets(){
TwitterUser o=新TwitterUser();
字符串m=o.getValue();
系统输出println(“Kida”+m);
//listview=this.getListView();
字符串ScreenName=m;
ConnectivityManager connMgr=(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=connMgr.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isConnected()){
新建DownloadTwitterTask().execute(屏幕名称);
}否则{
Log.v(Log_标签,“没有可用的网络连接”);
}
}
//使用异步任务下载Twitter用户的时间线
私有类DownloadTwitterTask扩展了AsyncTask{
最终静态字符串使用者_KEY=“GTRG54G45G45G45G54G45G54G45G45G45G54G45U”;
最终静态字符串使用者_SECRET=“s54g54g54g54g2hd5vx3rdyefekcodg”;
最终静态字符串TwitterTokenURL=”https://api.twitter.com/oauth2/token";
最终静态字符串TwitterStreamURL=”https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
私有进程对话;
@凌驾
//可以在这里使用UI线程
受保护的void onPreExecute(){
//this.progressDialog=progressDialog.show(Boys.this,“,”看看谁的背!!好的,让我看看我有什么给你);
试一试{
progressDialog=新建progressDialog(FragmentOne.this.getActivity(),AlertDialog.THEME\u HOLO\u DARK);
progressDialog.setUndeterminate(true);
progressDialog.setIndenderedRavable(getResources().getDrawable(R.drawable.loader_2));
setMessage(“请稍候!正在为您展开某些内容…”);
progressDialog.show();
progressDialog.setCancelable(假);
progressDialog.setCanceledOnTouchOutside(false);
}
捕获(例外e)
{
此.progressDialog.discouse()文件;
Toast.makeText(getActivity().getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
@凌驾
受保护的字符串doInBackground(字符串…屏幕名称){
字符串结果=null;
如果(screenNames.length>0){
结果=getTwitterStream(屏幕名称[0]);
}
返回结果;
}
//onPostExecute将JSON结果转换为Twitter对象(tweet的数组列表)
@凌驾
受保护的void onPostExecute(字符串结果){
Twitter twits=jsonToTwitter(结果);
//让我们也将结果写入控制台
用于(Tweet Tweet:twits){
Log.i(Log_标记,tweet.getText());
}
System.out.println(“Kamina”+twits);
//将tweet发送到适配器进行渲染
ArrayAdapter=新的ArrayAdapter(getActivity().getBaseContext(),R.layout.customgrid,R.id.text,twits);
setListAdapter(适配器);
此.progressDialog.discouse()文件;
}
//将JSON数据字符串转换为Twitter对象
私有Twitter(字符串结果){
Twitter twits=null;
if(result!=null&&result.length()>0){
试一试{
Gson Gson=新的Gson();
twits=gson.fromJson(结果,Twitter.class);
}捕获(非法状态例外){
//只吃例外
}
}
返回小枝;
}
//将JSON身份验证对象转换为经过身份验证的对象
私有身份验证jsonToAuthenticated(字符串授权){
认证的auth=null;
if(rawAuthorization!=null&&rawAuthorization.length()>0){
试一试{
Gson Gson=新的Gson();
auth=gson.fromJson(rawAuthorization,Authenticated.class);
}捕获(非法状态例外){
//只吃例外
}
}
返回auth;
}
私有字符串GetResponseBy(HttpRequestBase请求){
圣
<?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>
<?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>
 @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);
    }