在ListView的每个项目中添加点击监听器

4
我想在Android ListView项中添加可点击链接。每行ListView有5个项目,我只想让其中两个项目可点击,并使用putextras()意图在WebView中打开。我正在使用自定义适配器,请帮忙。
假设"链接1"是:"查看校对"(proofinglink)(在TextView中)和"链接2"是:"获取更多详细信息"(sitelink),我希望当我点击链接1时,它应该在WebView中打开其自己给定的URL。当我点击链接2时:它也应该在WebView中打开其自己给定的URL,使用putextras()意图。这是我的代码。
           package tipster;

            import java.io.BufferedReader;
            import java.io.IOException;
            import java.io.InputStream;
            import java.io.InputStreamReader;
            import java.io.UnsupportedEncodingException;
            import java.net.URI;
            import java.net.URISyntaxException;
            import java.util.ArrayList;
            import java.util.List;
            import newsletter.Latest_list;
            import newsletter.Webview_news;

            import org.apache.http.HttpEntity;
            import org.apache.http.HttpResponse;
            import org.apache.http.NameValuePair;
            import org.apache.http.client.ClientProtocolException;
            import org.apache.http.client.HttpClient;
            import org.apache.http.client.methods.HttpGet;
            import org.apache.http.impl.client.DefaultHttpClient;
            import org.apache.http.message.BasicNameValuePair;
            import org.json.JSONArray;
            import org.json.JSONException;
            import org.json.JSONObject;

            import android.app.Activity;
            import android.app.Dialog;
            import android.app.ProgressDialog;
            import android.content.Context;
            import android.content.Intent;
            import android.net.ConnectivityManager;
            import android.net.NetworkInfo;
            import android.os.AsyncTask;
            import android.os.Bundle;
            import android.view.Menu;
            import android.view.MenuItem;
            import android.view.View;
            import android.widget.AdapterView;
            import android.widget.AdapterView.OnItemClickListener;
            import android.widget.ListView;
            import android.widget.Toast;

            import com.example.newapp.R;

           public class Tipster extends Activity {
           ListView lv;
           ArrayList<Tipster_list>listitem;
           String title;
           String serviceUrl;

           @Override
           protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_tipster);

         if (isNetworkAvailable()) {
         // Execution here
        // Toast.makeText(this, "Network is Available!",
                  Toast.LENGTH_LONG).show();

        execute();

        title="Free Tip - Betfans";

        lv=(ListView) findViewById(R.id.listView_tipsterID);

        listitem=new ArrayList<Tipster_list>();
    }

 else {

   Toast.makeText(this, "Network is unavailable!",
  Toast.LENGTH_LONG).show();
 }


}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = manager.getActiveNetworkInfo();

    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }
    return isAvailable;
}

private void execute() {

    serviceUrl ="http://mobile.betfan.com/api/?      
  Action=top&type=default&key=MEu07MgiuWgXwJOo7Oe1aHL0yM8VvP";

    //Toast.makeText(LatestNews.this, serviceUrl, Toast.LENGTH_LONG).show();  


    class LoginAsync extends AsyncTask<String, Void, String>{

        private Dialog loadingDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loadingDialog = ProgressDialog.show(Tipster.this, "Please
           while wait", "Loading...");
        }

        @Override
        protected String doInBackground(String... params) {

            JSONObject jsonObject = new JSONObject();

            String dataString = jsonObject.toString();

            InputStream is = null;
            List<NameValuePair> nameValuePairs = new 
               ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("data", dataString));

            String result = null;

            try{



                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpRequest = new HttpGet();

                URI apiurl = new URI(serviceUrl);

                httpRequest.setURI(apiurl);

                HttpResponse response = httpClient.execute(httpRequest);

                HttpEntity entity = response.getEntity();

                is = entity.getContent();

                BufferedReader reader = new BufferedReader(new 
             InputStreamReader(is, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                result = sb.toString();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result){
            String s = result.trim();


            loadingDialog.dismiss();

                JSONObject respObject;
                try {
                    respObject = new JSONObject(s);
                    String active = respObject.getString("status_message");


                    if(active.equalsIgnoreCase("success")){
                     JSONArray array =     
                   respObject.getJSONArray("response");
                            for (int i =0; i<array.length();i++){

                         JSONObject jsonObject = array.getJSONObject(i);
                         String icon= jsonObject.getString("image");
                         String name = jsonObject.getString("name");
                         String total = jsonObject.getString("total");
                         String proofinglink = 
                       jsonObject.getString("proofinglink");
                         String sitelink = jsonObject.getString("sitelink");

                          listitem.add(new   
                  Tipster_list(icon,name,"+"+total,proofinglink,sitelink));

                        }
                         lv.setAdapter(new Tipster_adapter(Tipster.this,  
                 listitem));    

                    }else {
                        Toast.makeText(Tipster.this, "services received 
                  Fail", Toast.LENGTH_LONG).show();

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                lv.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                            int arg2, long arg3) {
                        // TODO Auto-generated method stub

                        String getName=listitem.get(arg2).getName();
                        String 
                 getproofing=listitem.get(arg2).getProofinglink();
                        String getsite=listitem.get(arg2).getSitelink();







                        Intent intent = new Intent(getApplicationContext(), 
             Tipster_webview.class);

                         intent.putExtra("gettproofing_URl",getproofing);
                         intent.putExtra("getsiteURL",getsite);
                        startActivity(intent);

                    }
                });

        }

    }

    LoginAsync la = new LoginAsync();
    la.execute();

  }  

我希望“proofinglink”和“sitelink”可点击并在Web视图中打开

这是自定义适配器

                public class Tipster_adapter extends BaseAdapter {
                Context context;
          ArrayList<Tipster_list>tipslist;

                public Tipster_adapter(Context context,
     ArrayList<Tipster_list> tipslist) {
    super();
    this.context = context;
    this.tipslist = tipslist;
 }



  @Override
  public int getCount() {
    // TODO Auto-generated method stub
    return tipslist.size();
 }

  @Override
  public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
  }

  @Override
  public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView==null){

        LayoutInflater inflater=(LayoutInflater)
    context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
      convertView=inflater.inflate(R.layout.activity_tipster_adapter
                 ,null); 


        ImageView icon=
      (ImageView)convertView.findViewById(R.id.icon_tipsterIconID);

        TextView name=(TextView) 
          convertView.findViewById(R.id.txt_name_tipsterID);
        TextView total=(TextView) 
     convertView.findViewById(R.id.txt_total_tipsterID);
        TextView proofingLink=(TextView) 
   convertView.findViewById(R.id.txt_proofinglink_tipsterID);
        TextView siteLink=(TextView) 
   convertView.findViewById(R.id.txt_sitelink_tipsterID);

        Tipster_list services=tipslist.get(position);
        Picasso.with(context).load(services.getImage()).into(icon);
        Log.d("Url",services.getImage());
        name.setText(services.getName());
        total.setText(services.getTotal());
        proofingLink.setText(services.getProofinglink());
        siteLink.setText(services.getSitelink());

        }



    return convertView;
   }

}
3个回答

0

你的代码没问题,你需要在适配器中为想要触发意图的视图添加一个监听器,例如:

inside your adapter getview method paste this code like this

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Tipster_list services=tipslist.get(position);
    if(services!=null){
        LayoutInflater inflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView=inflater.inflate(R.layout.activity_custom_adapter,null);
        ImageView icon=(ImageView)convertView.findViewById(R.id.icon_tipsterIconID);
        TextView name=(TextView) convertView.findViewById(R.id.txt_name_tipsterID);
        TextView total=(TextView) convertView.findViewById(R.id.txt_total_tipsterID);
        TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);
        TextView siteLink=(TextView) convertView.findViewById(R.id.txt_sitelink_tipsterID);
        Picasso.with(context).load(services.getImage()).into(icon);
        Log.d("Url",services.getImage());
        name.setText(services.getName());
        total.setText(services.getTotal());
        proofingLink.setText(services.getProofinglink());
        siteLink.setText(services.getSitelink());
        convertView.setTag(position);
        String getName=services.getName();
        final String getproofing=services.getProofinglink();
        final String getsite=services.getSitelink();
        proofingLink.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(context, Tipster_webview.class);
                 intent.putExtra("gettproofing_URl",getproofing);
                context.startActivity(intent);
            }
        });
        siteLink.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            Intent intent = new Intent(context, Tipster_webview.class);
                             intent.putExtra("site",getsite);
                            context.startActivity(intent);
                        }
                    });
        }



return convertView;
}

不写txt_name_tipsterID为什么会导致"convertView.findViewById(R.id.txt_name_tipsterID"无效?除此之外,当我将你的代码粘贴到适配器中时,还会出现许多其他错误。 @Mehroz Munir - sajid Hussain
我认为应该在 "public class Tipster extends Activity {}" 中使用,而不是在适配器中,因为 intent.putExtra("gettproofing_URl",getproofing); 已经在 Tipster 类中使用!而不是在适配器中。如果我在适配器中编写,那么如何获取 "getproofing" 的值?getproofing 在 tipster 类中从 json 获取值,请更新您的答案。 - sajid Hussain
不要在适配器中使用它,如果启动活动时出现错误,可以使用上下文。 - Mehroz Munir
Intent intent = new Intent(context.getApplicationContext(), Tipster_webview.class); intent.putExtra("gettproofing_URl",getproofing); intent.putExtra("getplatform", getsite); context.startActivity(intent); - Mehroz Munir
你的 Tipster_webview 类也应该是公共的,以便在适配器中访问它。 - Mehroz Munir
显示剩余6条评论

0
    TextView proofingLink=(TextView) convertView.findViewById(R.id.txt_proofinglink_tipsterID);

    proofingLink.setOnClickListener(new OnItemClickListener() {

     @Override
     public void onClick(View arg0) {

       String url = services.getProofinglink();
       Intent i = new Intent(Intent.ACTION_VIEW);
       i.setData(Uri.parse(url));
       startActivity(i);
          }
      });

0
TextView proofingLink=(TextView)
convertView.findViewById(R.id.txt_proofinglink_tipsterID);
proofingLink.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }
}); 
TextView siteLink=(TextView) 
convertView.findViewById(R.id.txt_sitelink_tipsterID);
siteLink.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}); 

我从JSON中获取了“proofinglink”和“sitelink”,现在我该如何将它们与FindViewById和SetOnclickListener绑定起来。请帮助我,我是新手,谢谢@shubham。 - sajid Hussain
在getView()方法中编写此代码,并且在该方法中还有链接。 - Shubham
我也在getview中编写,但没有帮助,它会出现错误。错误1:“重复的本地变量proofingLink”;错误2:“类型View中的方法setOnClickListener(View.OnClickListener)不适用于参数(new OnClickListener(){})”。 - sajid Hussain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接