How to show title of a row in a textview in Main Activity when an image in the row is clicked

ε祈祈猫儿з 提交于 2019-12-11 14:36:08

问题


I have a custom adapter with an image in each row.On clicking the image i would like to display the title of the row that the image is part of.

I have implemented an interface in my activity that allows me to display a relative layout whenever the image is clicked where the textview that displays the row title exists.This relative layout is in in my activity_main.xml.

Problem: I have been able to accomplish all his except that only the title of the first row is displayed across all the other image clicks in my listview.

Also: I know that setting listView.setOnItemSelectedListener(this); is the best way to go because this can handle the position of the title but i cannot use this as per my requirements.Is there a way to hack this?

So that my textview displays the title of the row that is different in each case?

MainActivity.java:

public class MainActivity extends ActionBarActivity implements FeedListAdapter.AdapterCallback {
    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    RelativeLayout error, player;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://10.0.3.2/main_feed_warship/main_feed.js";

    @SuppressLint("NewApi")

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        TextView mToolBarTextView = (TextView) findViewById(R.id.text_view_toolbar_title);
        mToolBarTextView.setText("Home");
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        player = (RelativeLayout) findViewById(R.id.player);
        player.setVisibility(View.GONE);

        ImageView cancel = (ImageView) findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                player.setVisibility(View.GONE);
            }
        });
        

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

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(URL_FEED);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    VolleyLog.d(TAG, "Response: " + response.toString());
                    if (response != null) {
                        parseJsonFeed(response);
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());

                }

                ;
            });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }

    }

    
    /**
     * Parsing json reponse and passing the data to feed view list adapter
     */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void onMethodCallback() {
      
      //On Image click this relative layout is called
      
        player.setVisibility(View.VISIBLE);
      
      //And the title of the row with the image that is clicked is displayed
      //Only the first row title is dispalyed across all image clicks
      
        String name = ((TextView) findViewById(R.id.name))
                .getText().toString();
        TextView title=(TextView)findViewById(R.id.music_title);
        title.setText(name);

    }
}

FeedListAdapter.java:

public class FeedListAdapter extends BaseAdapter {
    private Activity activity;
    private AdapterCallback mAdapterCallback;
    private LayoutInflater inflater;
    String title;
    private List<FeedItem> feedItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
        this.activity = activity;
        this.feedItems = feedItems;
        try {
            this.mAdapterCallback = ((AdapterCallback) activity);
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement AdapterCallback.");
        }
    }

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

    @Override
    public Object getItem(int location) {
        return feedItems.get(location);
    }

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

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

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.feed_item, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();

        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView timestamp = (TextView) convertView
                .findViewById(R.id.timestamp);
        TextView statusMsg = (TextView) convertView
                .findViewById(R.id.txtStatusMsg);
        TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
        FeedImageView feedImageView = (FeedImageView) convertView
                .findViewById(R.id.feedImage1);

        final FeedItem item = feedItems.get(position);

        name.setText(item.getName());
        String fontPath = "fonts/Lato-Light.ttf";

        // Loading Font Face
        Typeface tf = Typeface.createFromAsset(activity.getAssets(), fontPath);

        // Applying font
        name.setTypeface(tf);
        // Converting timestamp into x ago format
        CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
                Long.parseLong(item.getTimeStamp()),
                System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
        timestamp.setText(timeAgo);
        timestamp.setVisibility(View.GONE);
        // Chcek for empty status message
        if (!TextUtils.isEmpty(item.getStatus())) {
            statusMsg.setText(item.getStatus());
            statusMsg.setVisibility(View.GONE);
        } else {
            // status is empty, remove from view
            statusMsg.setVisibility(View.GONE);
        }

        // Checking for null feed url
        if (item.getUrl() != null) {
            url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
                    + item.getUrl() + "</a> "));

            // Making url clickable
            url.setMovementMethod(LinkMovementMethod.getInstance());
            url.setVisibility(View.GONE);
        } else {
            // url is null, remove from the view
            url.setVisibility(View.GONE);
        }


        // Feed image
        if (item.getImge() != null) {
            feedImageView.setImageUrl(item.getImge(), imageLoader);
            feedImageView.setVisibility(View.VISIBLE);
            feedImageView
                    .setResponseObserver(new FeedImageView.ResponseObserver() {
                        @Override
                        public void onError() {
                        }

                        @Override
                        public void onSuccess() {
                        }
                    });
        } else {
            feedImageView.setVisibility(View.GONE);
        }

//The image in each row that is clicked to call the method below from my activity

        ImageView play=(ImageView)convertView.findViewById(R.id.play);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    mAdapterCallback.onMethodCallback();

                } catch (ClassCastException exception) {
                }
            }
        });

        

        return convertView;
    }
    public static interface AdapterCallback {
        void onMethodCallback();
    }
   
    }

回答1:


This is a long shot, but did you try utilizing the Tag. It goes like this:

1- In your adapter, set the ImageView tag to be the TextView (title) id:

feedImageView.setTag(name.getId());

2- When the imageView is clicked, you get the tag (i.e. the id of the TextView).

feedImageView.getTag();

3- Now, you have the correct reference to your title.


I'm not sure if passing the TextView id will be enough, but I think utilizing the Tag is the way to go. You just need to figure out what you should pass, and where you should pass it. FYI, you could pass the title (as a string) in the tag!



来源:https://stackoverflow.com/questions/31903974/how-to-show-title-of-a-row-in-a-textview-in-main-activity-when-an-image-in-the-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!