Toast On ArrayAdapter

时间:2017-07-10 17:08:31

标签: java android xml listview

Toast On ArrayAdapter

如何在QuoteArrayAdapter上显示Toast消息OnClick textViewQuoteLike

显示消息Like is Done

public static ViewHolder create(RelativeLayout rootView) {
    ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
    TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
    TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
    final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
    TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
    TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
    final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);

    textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new GetDataLike().execute(textViewQuoteId.getText().toString());
            String currentLike = textViewQuoteLike.getText().toString();
            currentLike = currentLike.replace("پسندیدم (","");;
            currentLike = currentLike.replace(")","");;
            int newLike = Integer.valueOf(currentLike.toString()) + 1;
            textViewQuoteLike.setText("پسندیدم ("+newLike+")");
                /*Toast.makeText(Need Activity, "Like is done.",
                        Toast.LENGTH_LONG).show();*/
        }
    });
    return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}

如果在HomeFragment中有一种方法,请举例说明

QuoteArrayAdapter.java

package com.example.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;

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

import java.util.List;

public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {

    List<QuoteDataModel> modelList;
    Context context;
    private LayoutInflater mInflater;

    // Constructors
    public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
        super(context, 0, objects);
        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        modelList = objects;
    }

    @Override
    public QuoteDataModel getItem(int position) {
        return modelList.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder vh;
        if (convertView == null) {
            View view = mInflater.inflate(R.layout.quote_row, parent, false);
            vh = ViewHolder.create((RelativeLayout) view);
            view.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        QuoteDataModel item = getItem(position);

        vh.textViewQuoteContent.setText(item.getQuoteContent());
        vh.textViewProfileName.setText(item.getProfileName());
        vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
        vh.textViewQuoteCopy.setText("کپی کردن");
        vh.textViewQuoteShare.setText("اشتراک گزاری");
        vh.textViewQuoteId.setText(item.getQuoteId());
        Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);

        return vh.rootView;
    }

    private static class ViewHolder {
        public final RelativeLayout rootView;
        public final ImageView imageViewProfilePhoto;
        public final TextView textViewQuoteContent;
        public final TextView textViewProfileName;
        public final TextView textViewQuoteLike;
        public final TextView textViewQuoteCopy;
        public final TextView textViewQuoteShare;
        public final TextView textViewQuoteId;

        private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId) {
            this.rootView = rootView;
            this.imageViewProfilePhoto = imageViewProfilePhoto;
            this.textViewQuoteContent = textViewQuoteContent;
            this.textViewProfileName = textViewProfileName;
            this.textViewQuoteLike = textViewQuoteLike;
            this.textViewQuoteCopy = textViewQuoteCopy;
            this.textViewQuoteShare = textViewQuoteShare;
            this.textViewQuoteId = textViewQuoteId;
        }

        public static ViewHolder create(RelativeLayout rootView) {
            ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
            TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
            TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
            final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
            TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
            TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
            final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);

            textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    new GetDataLike().execute(textViewQuoteId.getText().toString());
                    String currentLike = textViewQuoteLike.getText().toString();
                    currentLike = currentLike.replace("پسندیدم (","");;
                    currentLike = currentLike.replace(")","");;
                    int newLike = Integer.valueOf(currentLike.toString()) + 1;
                    textViewQuoteLike.setText("پسندیدم ("+newLike+")");
                }
            });
            return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
        }
    }


    static class GetDataLike extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

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

            String quoteId = params[0];

            JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?platform=true&id="+quoteId);
            try {
                if (jsonObject != null) {
                    if(jsonObject.length() > 0) {
                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
                        int lenArray = array.length();
                        if(lenArray > 0) {
                            for(int jIndex = 0; jIndex < lenArray; jIndex++) {
                                JSONObject innerObject = array.getJSONObject(jIndex);
                                String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
                                return quote_like;
                            }
                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String aVoid) {
            super.onPostExecute(aVoid);
        }
    }

    public class CircleTransform implements Transformation {
        @Override
        public Bitmap transform(Bitmap source) {
            int size = Math.min(source.getWidth(), source.getHeight());

            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;

            Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
            if (squaredBitmap != source) {
                source.recycle();
            }

            Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());

            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            BitmapShader shader = new BitmapShader(squaredBitmap,
                    BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
            paint.setShader(shader);
            paint.setAntiAlias(true);

            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);

            squaredBitmap.recycle();
            return bitmap;
        }

        @Override
        public String key() {
            return "circle";
        }
    }
}

HomeFragment.java

package com.example;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;

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

import java.util.ArrayList;

public class HomeFragment extends Fragment {

    private ListView listView;
    private ArrayList<QuoteDataModel> list;
    private QuoteArrayAdapter adapter;
    private TextView likeCurrent;

    public HomeFragment() {
        // Required empty public constructor
    }

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

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

        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_home, null);

        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /**
         * Array List for Binding Data from JSON to this List
         */
        list = new ArrayList<>();

        adapter = new QuoteArrayAdapter(getActivity(), list);

        /**
         * Getting List and Setting List Adapter
         */
        listView = (ListView) getActivity().findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Snackbar.make(getActivity().findViewById(R.id.parentLayout), list.get(position).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
            }
        });

        /**
         * Check internet connection
         */
        if (!MainActivity.NetworkUtil.isOnline(getActivity().getApplicationContext())) {
            Toast.makeText(getActivity(), "اتصال به اینترنت برقرار نیست",
                    Toast.LENGTH_LONG).show();
        }

        new GetDataHome().execute();

        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            public void onScrollStateChanged(AbsListView view, int scrollState) {


            }

            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {

                if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
                {
                    new GetDataHome().execute();
                }
            }
        });

       /*
      likeCurrent = (TextView) getActivity().findViewById(R.id.textViewQuoteLike);

       likeCurrent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                likeCurrent.setText("Boiling Point K");
            }
        });*/


    }

    /**
     * Creating Get Data Task for Getting Data From Web
     */
    class GetDataHome extends AsyncTask<Void, Void, Void> {

        ContentLoadingProgressBar progressBar;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            /**
             * Progress Bar for User Interaction
             */
            progressBar = (ContentLoadingProgressBar) getActivity().findViewById(R.id.progress);
            progressBar.show();
        }

        @Nullable
        @Override
        protected Void doInBackground(Void... params) {

            /**
             * Getting JSON Object from Web Using okHttp
             */
            JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_home/?platform=true");

            try {
                /**
                 * Check Whether Its NULL???
                 */
                if (jsonObject != null) {
                    /**
                     * Check Length...
                     */
                    if(jsonObject.length() > 0) {
                        /**
                         * Getting Array named "Home" From MAIN Json Object
                         */
                        JSONArray array = jsonObject.getJSONArray(Keys.KEY_HOME);

                        /**
                         * Check Length of Array...
                         */
                        int lenArray = array.length();
                        if(lenArray > 0) {
                            for(int jIndex = 0; jIndex < lenArray; jIndex++) {

                                /**
                                 * Creating Every time New Object
                                 * and
                                 * Adding into List
                                 */
                                QuoteDataModel model = new QuoteDataModel();

                                /**
                                 * Getting Inner Object from contacts array...
                                 * and
                                 * From that We will get Name of that Contact
                                 *
                                 */
                                JSONObject innerObject = array.getJSONObject(jIndex);

                                String profile_photo = innerObject.getString(Keys.KEY_PROFILE_PHOTO);
                                String profile_name = innerObject.getString(Keys.KEY_PROFILE_NAME);
                                String profile_link = innerObject.getString(Keys.KEY_PROFILE_LINK);
                                String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
                                String quote_id = innerObject.getString(Keys.KEY_QUOTE_ID);
                                String quote_content = innerObject.getString(Keys.KEY_QUOTE_CONTENT);
                                String quote_category = innerObject.getString(Keys.KEY_QUOTE_CATEGORY);


                                /**
                                 * Getting Object from Object "other"
                                 */
                                //JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
                                //String other = otherObject.getString(Keys.KEY_NAME_SUB);


                                model.setProfilePhoto(profile_photo);
                                model.setProfileName(profile_name);
                                model.setProfileLink(profile_link);
                                model.setQuoteLike(quote_like);
                                model.setQuoteId(quote_id);
                                model.setQuoteContent(quote_content);
                                model.setQuoteCategory(quote_category);

                                /**
                                 * Adding data in List...
                                 */
                                list.add(model);
                            }
                        }
                    }
                } else {

                }
            } catch (JSONException je) {
                Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            /**
             * Progress Bar for User Interaction
             */
            progressBar.hide();

            /**
             * Checking if List size if more than zero then
             * Update ListView
             */
            if(list.size() > 0) {
                adapter.notifyDataSetChanged();
            } else {
                Snackbar.make(getActivity().findViewById(R.id.parentLayout), "مشکلی در اتصال به سرورهای سخنک رخ داده است!", Snackbar.LENGTH_LONG).show();
            }
        }
    }

}

quote_row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageViewProfilePhoto"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="5dp"
        android:layout_gravity="right"
        android:layout_alignParentRight="true"
        android:src="@drawable/empty_profile_photo" />

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/imageViewProfilePhoto">

        <TextView
            android:id="@+id/textViewQuoteContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:textIsSelectable="true"
            tools:text="Quote Content" />

        <TextView
            android:id="@+id/textViewProfileName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:textAppearance="?android:textAppearanceSmall"
            android:textIsSelectable="true"
            tools:text="Profile Name" />



        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true">
            <TextView
                android:id="@+id/textViewQuoteCopy"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:textAppearance="?android:textAppearanceSmall"
                android:clickable="true"
                tools:text="Copy" />

            <TextView
                android:id="@+id/textViewQuoteShare"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:textAppearance="?android:textAppearanceSmall"
                tools:text="Share" />

            <TextView
                android:id="@+id/textViewQuoteLike"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:textAppearance="?android:textAppearanceSmall"
                tools:text="Like" />

        </LinearLayout>

    </LinearLayout>

    <TextView
        android:text="TextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:id="@+id/textViewQuoteId"
        android:visibility="invisible" />

</RelativeLayout>

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/parentLayout"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">

<android.support.v4.widget.ContentLoadingProgressBar
    android:id="@+id/progress"
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:visibility="visible" />

<ListView app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="match_parent" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

您只需context,所以:

Toast.makeText(rootView.getContext(), "Like is done.",
                        Toast.LENGTH_LONG).show();

但是你需要先将rootView设为final:

public static ViewHolder create(final RelativeLayout rootView){...
                                 ^^