在按钮onclick方法中访问listview中的特定项目视图

时间:2015-06-07 14:40:06

标签: java android listview textview



public class DisplayAllBets extends ActionBarActivity {
    private String user1 = "user";
    private static String url_all_games = "**";
    private static String url_update_bet = "**";

    // Progress Dialog
    private ProgressDialog pDialog;
    private ProgressDialog tDialog;
    private BetDisplayer currentitem;
    private HashMap<String, String> userhash = new HashMap<>();

    private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
    private HashMap<String, String> useroutcomes = new HashMap<>();
    private HashMap<String, String> finalhash = new HashMap<>();

    private ArrayList<Map<String, String>> passtocheck = new ArrayList<>();
    private HashMap<String, HashMap<String, String>> passtocheckver2 = new HashMap<>();
    private String name;
    private HashMap<String, String> allopens = new HashMap<>();
    JSONParser jsonParser = new JSONParser();


    // Creating JSON Parser object
    JSONParsers jParser = new JSONParsers();

    ArrayList<HashMap<String, String>> bet;

    // url to get all products list

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_BET = "bet";
    private static final String TAG_ID = "id";
    private static final String TAG_STAKE = "stake";
    private static final String TAG_USER = "user";
    private static final String TAG_RETURNS = "returns";
    private static final String TAG_TEAMS = "teams";
    private static final String TAG_STATUS = "status";


    // products JSONArray
    JSONArray allgames = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_display_all_bets);


        name = (getIntent().getExtras().getString("user")).toLowerCase();
        Log.d("name", name);
        // Hashmap for ListView
        bet = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllGames().execute();

    }

    /**
     * Background Async Task to Load all product by making HTTP Request
     */
    class LoadAllGames extends AsyncTask<String, String, String> {
        private String id;
        private String stake;
        private String user;
        private String returns;
        private String teams;
        private String status;


        //  *//**
        //   * Before starting background thread Show Progress Dialog
        //    *//*
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(DisplayAllBets.this);
            pDialog.setMessage("Loading Games. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
        }

        //  *//**
        //    * getting All products from url
        //    *//*
        protected String doInBackground(String... args) {
            // Building Parameters
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url_all_games);
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("email", name));
            try {
                post.setEntity(new UrlEncodedFormEntity(params));
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            try {
                HttpResponse response = client.execute(post);
                Log.d("Http Post Response:", response.toString());
                HttpEntity httpEntity = response.getEntity();
                InputStream is = httpEntity.getContent();
                JSONObject jObj = null;
                String json = "";
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {

                        if (!line.startsWith("<", 0)) {
                            if (!line.startsWith("(", 0)) {
                                sb.append(line + "\n");
                            }
                        }
                    }

                    is.close();
                    json = sb.toString();
                    json = json.substring(json.indexOf('{'));
                    Log.d("sb", json);

                } catch (Exception e) {
                    Log.e("Buffer Error", "Error converting result " + e.toString());
                }

                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }

                // return JSON String
                Log.d("json", jObj.toString());
                try {
                    allgames = jObj.getJSONArray(TAG_BET);
                    Log.d("allgames", allgames.toString());
                    ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
                    // looping through All Products
                    for (int i = 0; i < allgames.length(); i++) {
                        JSONObject c = allgames.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String user = c.getString(TAG_USER);
                        String returns = c.getString(TAG_RETURNS);
                        String stake = c.getString(TAG_STAKE);
                        String status = c.getString(TAG_STATUS);
                        String Teams = c.getString(TAG_TEAMS);
                        Log.d("id", id);
                        Log.d("user", user);
                        Log.d("returns", returns);
                        Log.d("stake", stake);
                        Log.d("status", status);
                        Log.d("teams", Teams);


                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_TEAMS, Teams);
                        map.put(TAG_USER, user);
                        map.put(TAG_RETURNS, returns);
                        map.put(TAG_STAKE, stake);
                        map.put(TAG_STATUS, status);
                        if (status.equals("open")) {
                            useroutcomes.put(id.substring(0, 10), Teams);
                        }
                        listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, Teams));


                        // adding HashList to ArrayList
                        bet.add(map);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }


            return "";
        }


        @Override
        protected void onPostExecute(String param) {


            // dismiss the dialog after getting all products
            // updating UI from Background Thread
            String ultparam = "";
            int i = 0;
            for (HashMap<String, String> a : bet) {
                String teams = a.get(TAG_TEAMS);

                Map<String, String> listofteams = new HashMap<>();

                Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
                Matcher m = p.matcher(teams);
                Log.d("printa", teams);
                while (m.find()) {
                    listofteams.put(m.group(1), m.group(2));
                }
                Log.d("dede", listofteams.toString());
                String c = "";
                for (String x : listofteams.keySet()) {
                    String b = x + ",";
                    c = c + b;
                }
                Log.d("C", c);
                c = c.substring(0, c.lastIndexOf(","));
                //    Log.d("Cproc", c);
                if (a.get(TAG_STATUS).equals("open")) {
                    ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
                    passtocheck.add(listofteams);
                    allopens.put(Integer.toString(i), a.get(TAG_STATUS));
                    i++;
                }

                i++;

            }
            ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
            Log.d("ULTPARAM", ultparam);
            CheckBet checker = new CheckBet(ultparam, passtocheck);
            HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
            Log.d("Finaloutcomes", finaloutcomes.toString());
            for (String x : finaloutcomes.keySet()) {
                    for (int p = 0; p < listwriter.size(); p++) {
                        if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
                            String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
                            String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
                            for (int r = 0; r < finaloutcomearray.length; r++) {
                                Log.d("finaloutcomearray", finaloutcomearray[r]);
                                Log.d("useroutcomearray", useroutcomearray[r]);
                                String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
                                String[] induseroutcomearray = useroutcomearray[r].split("\\)");
                                for (int d = 0; d < indfinaloutcomesarray.length; d++) {
                                    Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
                                    Log.d("induseroutcome", induseroutcomearray[d]);
                                    finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
                                    userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));

                                }
                            }
                            Log.d("FINALHASHfinal", finalhash.toString());
                            Log.d("USERHASHfinal", userhash.toString());
                            listwriter.get(p).setStatus("won");
                            for (String id : userhash.keySet()) {
                                if (finalhash.get(id).equals("null")){
                                    listwriter.get(p).setStatus("open");
                                }
                                else if (!(finalhash.get(id).equals(userhash.get(id)))) {
                                    listwriter.get(p).setStatus("lost");
                                    break;
                                }

                            }
                            finalhash.clear();
                            userhash.clear();
                        currentitem = listwriter.get(p);
                           new UpdateBetStatus().execute();
                        }
                    }
                }

            Log.d("USEROUTCOMES", useroutcomes.toString());


            PopulateList();

        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_display_all_bets, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    class UpdateBetStatus extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * *
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tDialog = new ProgressDialog(DisplayAllBets.this);
            tDialog.setMessage("Loading your bets! Good luck!");
            tDialog.setIndeterminate(false);
            tDialog.setCancelable(true);
        }

        /**
         * Creating product
         * *
         */
        protected String doInBackground(String... args) {


            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("id", currentitem.getId()));
            params.add(new BasicNameValuePair("stake", Integer.toString(currentitem.getStake())));
            params.add(new BasicNameValuePair("user", name));
            params.add(new BasicNameValuePair("returns", Integer.toString(currentitem.getReturns())));
            params.add(new BasicNameValuePair("teams", currentitem.getSelections()));
            params.add(new BasicNameValuePair("status", currentitem.getStatus()));


            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_update_bet,
                    "POST", params);

            // check log cat fro response
            Log.d("Printing", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);


            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * * * *
         */
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done

        }
    }


    private class MyListAdapter extends ArrayAdapter<BetDisplayer> {
        public MyListAdapter() {
            super(DisplayAllBets.this, R.layout.activity_singletotalbet, listwriter);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            if (itemView == null) {
                itemView = getLayoutInflater().inflate(R.layout.activity_singletotalbet, parent, false);
            }
            BetDisplayer currentwriter = listwriter.get(position);
            Log.d("TESTING", currentwriter.getSelections());
            Button v = (Button) itemView.findViewById(R.id.detailsbutton);
            v.setTag(Integer.toString(position));
            Log.d("TESTING2", currentwriter.getSelections());
            String selections = currentwriter.getSelections();
            int numberofselections = 0;
            for (int i = 0; i < selections.length(); i++) {
                if (selections.charAt(i) == '/') {
                    numberofselections++;
                }
            }
            if (numberofselections == 1) {
                TextView descriptor = (TextView) itemView.findViewById(R.id.no);
                descriptor.setText("Single");
            } else if (numberofselections == 2) {
                TextView descriptor = (TextView) itemView.findViewById(R.id.no);
                descriptor.setText("Double");
            } else if (numberofselections == 3) {
                TextView descriptor = (TextView) itemView.findViewById(R.id.no);
                descriptor.setText("Treble");
            } else {
                TextView descriptor = (TextView) itemView.findViewById(R.id.no);
                descriptor.setText("Accumulator" + "(" + numberofselections + ")");
            }
            TextView status = (TextView) itemView.findViewById(R.id.status);
            status.setText(currentwriter.getStatus());
            return itemView;
        }
    }

    private void PopulateList() {
        ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
        final ListView list = (ListView) findViewById(R.id.betslistviews);
        list.setAdapter(adapter);
    }
           public void Viewdetails(View v) {
           Button b = (Button) v;
           int position = Integer.parseInt((String) v.getTag());
           final ListView list = (ListView) findViewById(R.id.betslistviews);
           String stake;
           String winnings;
           String token;
           String teams;
           String typeofbet;
           list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

               public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {

                   TextView status = (TextView) v.findViewById(R.id.status);
                   Log.d("STATUSTESTING",status.getText().toString());

               }
       });
    }
&#13;
&#13;
&#13;

我有一个填充的列表视图。列表中的每个项目都包含一个按钮和几个TextView,格式如下。

enter image description here

我创建了一个在单击任何按钮时运行的方法。我需要它做的是在listview中的那个位置检索特定的itemView,这样我就可以访问该itemview中的TextViews。这是我的代码,但它不是在工作。

&#13;
&#13;
  public void Viewdetails(View v) {
       Button b = (Button) v;
       int position = Integer.parseInt((String) v.getTag());
       final ListView list = (ListView) findViewById(R.id.betslistviews);
       String stake;
       String winnings;
       String token;
       String teams;
       String typeofbet;
       list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

           public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {

               View selItem = (View) list.getItemAtPosition(position);
               TextView status = (TextView) selItem.findViewById(R.id.status);
               Log.d("STATUSTESTING",status.getText().toString());

           }
   });
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

假设您的ListView侦听器在此处启动。

   list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

       public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {

           View selItem = (View) list.getItemAtPosition(position);
           TextView status = (TextView) selItem.findViewById(R.id.status);
           Log.d("STATUSTESTING",status.getText().toString());

       }
  });

你不必写

View selItem = (View) list.getItemAtPosition(position); 

因为您已经从重写的onItemClick方法引用了ListView中的特定View。

因此,您可以跳过该行并直接访问TextView

TextView status = (TextView) v.findViewById(R.id.status);

最后代码就像

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

       public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {

           //Already got reference to View v
           TextView status = (TextView) v.findViewById(R.id.status);
           Log.d("STATUSTESTING",status.getText().toString());

       }
  });

答案 1 :(得分:0)

要捕获onListItemClick,请在PopulateList()方法中添加侦听器:

private void PopulateList() {
        ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
        final ListView list = (ListView) findViewById(R.id.betslistviews);
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

           public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
               // Change children of list item here
               TextView status = (TextView) v.findViewById(R.id.status);
               Log.d("STATUSTESTING",status.getText().toString());

           }
        });
    }

要在适配器的getView()方法中找到您需要的列表项中的单击按钮,请将按键侦听器添加到按钮:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Button v = (Button) itemView.findViewById(R.id.detailsbutton);
    v.setOnClickListener(new View.OnClickListener() {

       @Override
       public void onClick(View v) {
           // Handle button click

       }
    });
}

修改

要存储数据,请在“活动”和“设置器”中为其创建字段:

private String text1;
private String text2;

public void setText1(String text){
    text1 = text;
}

public void setText2(String text){
    text2 = text;
}

然后在按钮单击侦听器中设置它:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        TextView tv1 = (TextView) itemView.findViewById(R.id.textview1_id);
        TextView tv2 = (TextView) itemView.findViewById(R.id.textview2_id);
        Button v = (Button) itemView.findViewById(R.id.detailsbutton);
        v.setOnClickListener(new View.OnClickListener() {

           @Override
           public void onClick(View v) {
               setText1(tv1.getText());
               setText2(tv2.getText());
           }
        });
    }