如何设置信息查看listadapter [英] How to set View for listadapter

查看:120
本文介绍了如何设置信息查看listadapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我试着与大家分享按钮文本 ListAdapter.java
不过,这并不工作,我如何设置观的onclick无效的按钮?
 我使用的片段对列表
看到我的code:

Hi I try to share a text with button in ListAdapter.java : But it doesn't work How can I set View in Onclick void for button ? I use fragment for lists see my code :

package com.kamalan.phpandroidapi;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class VoteListAdapter extends BaseAdapter {

//  protected static final Context VoteListAdapter.this = null;

    private final String TAG = "*** VoteListAdapter ***";

    private LayoutInflater myInflater;
    private List<Vote> vote;

    public VoteListAdapter(Context context) {
        myInflater = LayoutInflater.from(context);

    }

    public void setData(List<Vote> vote) {
        this.vote = vote;
    }


    @Override
    public int getCount() {
        return vote.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;        

        if (convertView == null) {
            convertView = myInflater.inflate(R.layout.row, null);
            holder      = new ViewHolder();
            holder.tvName      = (TextView)     convertView.findViewById(R.id.tvName);
            holder.tvComment   = (TextView)     convertView.findViewById(R.id.tvComment);
            holder.tvDate      = (TextView)     convertView.findViewById(R.id.tvDate);
            holder.ratingBar   = (RatingBar)    convertView.findViewById(R.id.ratingBar);
            holder.sharebtn   = (Button)    convertView.findViewById(R.id.sharebtn);        
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tvName.setText(vote.get(position).getName());
        holder.tvComment.setText(vote.get(position).getComment());
        holder.tvDate.setText(getFormatedDate(vote.get(position).getPublishDate()));
        holder.ratingBar.setRating(Integer.parseInt(vote.get(position).getRate()));
        OnClickListener clickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {

                    Context context = v.getContext();
                    String text = (String) holder.tvComment.getText();
                    //Toast.makeText(context, ab, Toast.LENGTH_LONG).show();
                    Intent i = new Intent(Intent.ACTION_SEND);
                    i.setType("text/plain");
                    i.putExtra(Intent.EXTRA_TEXT,text);
                    try {
                         context.startActivity(Intent.createChooser(i, "Share"));
                    } catch (android.content.ActivityNotFoundException ex) {
                         ex.printStackTrace();
                    }

            }
        };


        holder.sharebtn.setOnClickListener(clickListener);
        return convertView;
    }




    private String getFormatedDate(String date) {
        String myDate = null;

        try {
            Date oldDate = new SimpleDateFormat("yy-mm-dd hh:mm:ss").parse(date);
            myDate = new SimpleDateFormat("dd MMM yyyy").format(oldDate);
        } catch (ParseException e) {
            myDate = "";
            e.printStackTrace();
        }

        return myDate;
    }



    static class ViewHolder {
        public Button sharebtn;
        TextView  tvName;
        TextView  tvComment;
        TextView  tvDate;
        RatingBar ratingBar;
    }
}

和FragmentComment.java:

and FragmentComment.java :

package com.kamalan.phpandroidapi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.kamalan.phpandroidapi.FragmentForm.OnSendingRequestToServer;
//import com.kamalan.phpandroidapi.FragmentForm.SendFormTask;

import android.app.ActionBar;
import android.app.Activity; 
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentComment extends Fragment {

    private final String TAG = "FragmentComment";

    private OnSendingRequestToServer onRequestToServer;
    private Context context;
    private Spinner spinner;
    private ListView listView;
    private List<Vote> voteList;
    private VoteListAdapter listAdapter;
    int ab = 1;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            onRequestToServer = (OnSendingRequestToServer) activity;
        } catch (ClassCastException e) {
              throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
        }

        context = activity.getApplicationContext();

        Log.d(TAG, "Fragment attached to activity.");
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View view = inflater.inflate(R.layout.fragment_comments, container, false);     
        spinner = (Spinner) view.findViewById(R.id.spinner);
        final TextView refresh = (TextView) view.findViewById(R.id.closetag);
        refresh.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

            //  ActionBar actionBar = context.getSupportActionBar();
                  //getSupportActionBar();
                //  actionBar.hide(); 


                //android.app.ActionBar bar = getActivity().getActionBar();
                //bar.hide();
                 if (ab == 1){
                    ab = 0;
                    refresh.setText("کوچک کردن");
                    spinner.setVisibility(View.GONE);
                    android.app.ActionBar bar = getActivity().getActionBar();
                    bar.hide();
                 }else{
                    ab = 1;
                    refresh.setText("تمام صفحه");
                    spinner.setVisibility(View.VISIBLE);
                    android.app.ActionBar bar = getActivity().getActionBar();
                    bar.show(); 
                 }

            }
        }); 

    //  TextView tvComment = (TextView) view.findViewById(R.id.tvComment);



        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {




            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String deviceId = "all";

                voteList.clear();

                if(pos == 1){
                    //deviceId = getDeviceId();
                    deviceId = "c1";
                }else if(pos == 2){
                    deviceId = "c2";                
                }else if(pos == 3){
                    deviceId = "c3";                
                }else if(pos == 4){
                    deviceId = "c4";                
                }else if(pos == 5){
                    deviceId = "c5";                
                }else if(pos == 6){
                    deviceId = "c6";                
                }else if(pos == 7){
                    deviceId = "c7";                
                }else if(pos == 8){
                    deviceId = getDeviceId();               
                }
                voteList.clear();
                new RequestVoteTask(deviceId).execute();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });

        listView = (ListView) view.findViewById(R.id.listView);

        return view;
    }

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

        voteList = new ArrayList<Vote>();

        listAdapter = new VoteListAdapter(context);


    }

    private String getDeviceId() {
        return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
    }



    /*----------------------------------------------------------------------------
     * This method is responsible for creating another thread in parallel with
     * main UI thread in order to send a request to server and get data (if any).
     * ---------------------------------------------------------------------------*/
    public class RequestVoteTask extends AsyncTask<Void, Void, Boolean> {       
        String deviceId;

        RequestVoteTask(String deviceId) {
            this.deviceId = deviceId;
        }

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "RequestVoteTask is about to start...");

            onRequestToServer.DisplayLoding(true);
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean status = false; 
            HttpURLConnection urlConnection = null;

            try {
                URL url = new URL(LinkManager.getCommentAPI(deviceId));
                Log.d(TAG, "Try to open: " + url.toString());
                urlConnection = (HttpURLConnection) url.openConnection();
                int responseCode = urlConnection.getResponseCode();
                Log.d(TAG, "Response code is: " + responseCode);

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    if (in != null) {
                        StringBuilder strBuilder = new StringBuilder();
                        // Read character by character              
                        int ch = 0;
                        while ((ch = in.read()) != -1)
                            strBuilder.append((char) ch);

                        // get returned message and show it
                        String response = strBuilder.toString();
                        Log.d("Server response:", response);

                        JSONObject jObject = new JSONObject(response);
                        JSONArray jsonArray = jObject.getJSONArray("posts");
                        for(int i=0; i<jsonArray.length(); i++){
                            Vote vote = new Vote();
                            vote.setDeviceId(jsonArray.getJSONObject(i).getString("DeviceId"));
                            vote.setName(jsonArray.getJSONObject(i).getString("FullName"));
                            vote.setRate(jsonArray.getJSONObject(i).getString("Rate"));
                            vote.setComment(jsonArray.getJSONObject(i).getString("Comment"));
                            vote.setPublishDate(jsonArray.getJSONObject(i).getString("PublishTime"));

                            voteList.add(vote);
                        }

                        if(voteList.size() >= 1)
                            status = true;
                    }

                    in.close();
                }
            }
            catch(MalformedURLException e){
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            finally {
                urlConnection.disconnect();
            }

            return status;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            Log.d(TAG, "RequestVoteTask finished its task.");

            onRequestToServer.DisplayLoding(false);

            if(!result)
                Toast.makeText(context, "جکی موجود نیست", Toast.LENGTH_LONG).show();

//          for(int i=0; i<voteList.size(); i++)
//              Log.d("Item " + i, voteList.get(i).toString());

            listAdapter.setData(voteList);
            listView.setAdapter(listAdapter);

        }



    }

}

我尝试写getView或膨胀,...但它不工作

I try to write getView or inflate and ... but it doesn't work

推荐答案

试试这个办法,希望这将帮助你解决你的问题。

public class VoteListAdapter extends BaseAdapter {

    private final String TAG = "*** VoteListAdapter ***";
    private Context context;
    private ArrayList<Vote> votes;

    public VoteListAdapter(Context context,ArrayList<Vote> votes) {
        this.context =context;
        this.votes =votes;

    }

    @Override
    public int getCount() {
        return votes.size();
    }

    @Override
    public Object getItem(int position) {
        return votes.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder      = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.row, null);
            holder.tvName      = (TextView) convertView.findViewById(R.id.tvName);
            holder.tvComment   = (TextView) convertView.findViewById(R.id.tvComment);
            holder.tvDate      = (TextView) convertView.findViewById(R.id.tvDate);
            holder.ratingBar   = (RatingBar)convertView.findViewById(R.id.ratingBar);
            holder.sharebtn   = (Button) convertView.findViewById(R.id.sharebtn);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tvName.setText(votes.get(position).getName());
        holder.tvComment.setText(votes.get(position).getComment());
        holder.tvDate.setText(getFormatedDate(votes.get(position).getPublishDate()));
        holder.ratingBar.setRating(Integer.parseInt(votes.get(position).getRate()));
        holder.sharebtn.setOnClickListener( new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_TEXT,votes.get(position).getComment());
                try {
                    context.startActivity(Intent.createChooser(i, "Share"));
                } catch (android.content.ActivityNotFoundException ex) {
                    ex.printStackTrace();
                }

            }
        });
        return convertView;
    }




    private String getFormatedDate(String date) {
        String myDate = null;

        try {
            Date oldDate = new SimpleDateFormat("yy-mm-dd hh:mm:ss").parse(date);
            myDate = new SimpleDateFormat("dd MMM yyyy").format(oldDate);
        } catch (ParseException e) {
            myDate = "";
            e.printStackTrace();
        }

        return myDate;
    }



    static class ViewHolder {
        Button sharebtn;
        TextView  tvName;
        TextView  tvComment;
        TextView  tvDate;
        RatingBar ratingBar;
    }
}

public class FragmentComment extends Fragment {

    private final String TAG = "FragmentComment";

    private OnSendingRequestToServer onRequestToServer;
    private Context context;
    private Spinner spinner;
    private ListView listView;
    private List<Vote> voteList;
    private VoteListAdapter listAdapter;
    int ab = 1;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            onRequestToServer = (OnSendingRequestToServer) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
        }

        context = activity.getApplicationContext();

        Log.d(TAG, "Fragment attached to activity.");
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

        View view = inflater.inflate(R.layout.fragment_comments, container, false);
        spinner = (Spinner) view.findViewById(R.id.spinner);
        final TextView refresh = (TextView) view.findViewById(R.id.closetag);
        refresh.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                //  ActionBar actionBar = context.getSupportActionBar();
                //getSupportActionBar();
                //  actionBar.hide(); 


                //android.app.ActionBar bar = getActivity().getActionBar();
                //bar.hide();
                if (ab == 1){
                    ab = 0;
                    refresh.setText("کوچک کردن");
                    spinner.setVisibility(View.GONE);
                    android.app.ActionBar bar = getActivity().getActionBar();
                    bar.hide();
                }else{
                    ab = 1;
                    refresh.setText("تمام صفحه");
                    spinner.setVisibility(View.VISIBLE);
                    android.app.ActionBar bar = getActivity().getActionBar();
                    bar.show();
                }

            }
        });

        //  TextView tvComment = (TextView) view.findViewById(R.id.tvComment);



        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {




            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                String deviceId = "all";

                voteList.clear();

                if(pos == 1){
                    //deviceId = getDeviceId();
                    deviceId = "c1";
                }else if(pos == 2){
                    deviceId = "c2";
                }else if(pos == 3){
                    deviceId = "c3";
                }else if(pos == 4){
                    deviceId = "c4";
                }else if(pos == 5){
                    deviceId = "c5";
                }else if(pos == 6){
                    deviceId = "c6";
                }else if(pos == 7){
                    deviceId = "c7";
                }else if(pos == 8){
                    deviceId = getDeviceId();
                }
                voteList.clear();
                new RequestVoteTask(deviceId).execute();

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {

            }
        });

        listView = (ListView) view.findViewById(R.id.listView);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        voteList = new ArrayList<Vote>();
    }

    private String getDeviceId() {
        return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
    }



    /*----------------------------------------------------------------------------
     * This method is responsible for creating another thread in parallel with
     * main UI thread in order to send a request to server and get data (if any).
     * ---------------------------------------------------------------------------*/
    public class RequestVoteTask extends AsyncTask<Void, Void, Boolean> {
        String deviceId;

        RequestVoteTask(String deviceId) {
            this.deviceId = deviceId;
        }

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "RequestVoteTask is about to start...");

            onRequestToServer.DisplayLoding(true);
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean status = false;
            HttpURLConnection urlConnection = null;

            try {
                URL url = new URL(LinkManager.getCommentAPI(deviceId));
                Log.d(TAG, "Try to open: " + url.toString());
                urlConnection = (HttpURLConnection) url.openConnection();
                int responseCode = urlConnection.getResponseCode();
                Log.d(TAG, "Response code is: " + responseCode);

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    if (in != null) {
                        StringBuilder strBuilder = new StringBuilder();
                        // Read character by character              
                        int ch = 0;
                        while ((ch = in.read()) != -1)
                            strBuilder.append((char) ch);

                        // get returned message and show it
                        String response = strBuilder.toString();
                        Log.d("Server response:", response);

                        JSONObject jObject = new JSONObject(response);
                        JSONArray jsonArray = jObject.getJSONArray("posts");
                        for(int i=0; i<jsonArray.length(); i++){
                            Vote vote = new Vote();
                            vote.setDeviceId(jsonArray.getJSONObject(i).getString("DeviceId"));
                            vote.setName(jsonArray.getJSONObject(i).getString("FullName"));
                            vote.setRate(jsonArray.getJSONObject(i).getString("Rate"));
                            vote.setComment(jsonArray.getJSONObject(i).getString("Comment"));
                            vote.setPublishDate(jsonArray.getJSONObject(i).getString("PublishTime"));

                            voteList.add(vote);
                        }

                        if(voteList.size() >= 1)
                            status = true;
                    }

                    in.close();
                }
            }
            catch(MalformedURLException e){
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            catch (JSONException e) {
                e.printStackTrace();
            }
            finally {
                urlConnection.disconnect();
            }

            return status;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            Log.d(TAG, "RequestVoteTask finished its task.");

            onRequestToServer.DisplayLoding(false);

            if(!result)
                Toast.makeText(context, "جکی موجود نیست", Toast.LENGTH_LONG).show();

//          for(int i=0; i<voteList.size(); i++)
//              Log.d("Item " + i, voteList.get(i).toString());
            listAdapter = new VoteListAdapter(context,voteList);
            listView.setAdapter(listAdapter);
        }
    }
}

这篇关于如何设置信息查看listadapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆