Den richtigen Content aus einer listview in einem Fragment laden

  • Antworten:9
Antonio P.
  • Forum-Beiträge: 113

09.05.2014, 10:03:15 via Website

Hallo

ich habe eine Frage bezüglich Umgang mit listview und Fragmenten. Ich habe eine listview mit zehn verschiedenen items. Nun möchte ich, dass beim anklicken von z.B. item3 soll im darauffolgenden Fragment der richtige Inhalt geladen werden.

Ich kann mir nicht vorlstellen, dass ich für jedes item ein eigenes Fragment implementieren soll. Geht das irgendwie auch anders. Mit einem Interface?

Ein Code Beispiel wäre super.

Danke im voraus.

Mit freundlichen Grüßen
Antonio

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

09.05.2014, 10:05:15 via Website

Soll die oberfläche bei Allen Items einheitlich sein?
Wenn dann kannst du ein Fragment machen und dieses je nach Listeintrag mit anderne Daten füllen

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Antonio P.
  • Forum-Beiträge: 113

09.05.2014, 10:09:51 via Website

Genau, das Layout soll einheitlich für jedes Item sein. Ich möchte zu jedem item um die 20 Bilder(.png) in einer Gridview laden.

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

09.05.2014, 10:11:44 via Website

Dann machst du ein Fragment, dass dann so Flexibel ist, dass du bei jedem ListEintrag die entsprechenden Bilder laden kannst?
Wie würdest du das angehen?

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Antonio P.
  • Forum-Beiträge: 113

09.05.2014, 10:15:25 via Website

Ich würde jedes mal abfragen welches item geklickt wurde und in einer Methode (welche?) des Fragments die id übergeben. Wie ich die Bilder aber lade, das weiß ich nicht. Ich habe mich über Content Provider informiert. Leider weiß ich nicht ob es das richtige ist.

Hast du Tipps für mich?

EDIT:
Ich würde nicht über Intents die Bilder übergeben-

— geändert am 09.05.2014, 10:16:03

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

09.05.2014, 10:21:48 via Website

In deiner ListActivity brauchst du einen Click Listenener, indem du dann auswertest welches Item gecklickt wurde.
ändern sich die Bilder immer, oder sind das immer die gleichen Drawables pro Item (ist aber egal wenn die bei unterschiedlichen Items auch unterschiedliche Bilder haben)
Wichtig ist nur, dass du dem Fragment irgendwie die Drawable IDs übergibst.
Am besten über ein Integer Array

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Antonio P.
  • Forum-Beiträge: 113

09.05.2014, 10:28:55 via Website

Danke für die Antwort erstmals.
Die Listview und die Gridview, werden in zwei verschiedene Fragmenten (fragment_list und fragment_grid) implementiert, aber in der selben Activity.

Wenn ich nun die Inhalte von fragment_grid in einer zweiten Activity laden will soll ich das etwas beachten bezüglich LifeCycle der ersten Activity oder kann ich die gleiche Vorgehensweise mit dem ClickListener anwenden?

Die Bilder ändern sich, je nachdem welches item geklickt wurde.

Ich werde mich mal über Integer Array informieren.

Danke

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

09.05.2014, 13:51:42 via Website

Dan poste mal bitte den Code deines OnClick Listeners + Fragment Code.

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten
Antonio P.
  • Forum-Beiträge: 113

09.05.2014, 14:11:42 via Website

package com.example.test1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.test1.dummy.DummyContent;

/**
* A list fragment representing a list of Items. This fragment also supports
* tablet devices by allowing list items to be given an 'activated' state upon
* selection. This helps indicate which item is currently being viewed in a
* {@link ItemDetailFragment}.
* <p>
* Activities containing this fragment MUST implement the {@link Callbacks}
* interface.
*/
public class ItemListFragment extends ListFragment {

/**
 * The serialization (saved instance state) Bundle key representing the
 * activated item position. Only used on tablets.
 */
private static final String STATE_ACTIVATED_POSITION = &quot;activated_position&quot;;

/**
 * The fragment's current callback object, which is notified of list item
 * clicks.
 */
private Callbacks mCallbacks = sDummyCallbacks;

/**
 * The current activated item position. Only used on tablets.
 */
private int mActivatedPosition = ListView.INVALID_POSITION;

/**
 * A callback interface that all activities containing this fragment must
 * implement. This mechanism allows activities to be notified of item
 * selections.
 */
public interface Callbacks {
    /**
     * Callback for when an item has been selected.
     */
    public void onItemSelected(String id);
}

/**
 * A dummy implementation of the {@link Callbacks} interface that does
 * nothing. Used only when this fragment is not attached to an activity.
 */
private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(String id) {
    }
};

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ItemListFragment() {
}

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

    // TODO: replace with a real list adapter.
    setListAdapter(new ArrayAdapter&lt;DummyContent.DummyItem&gt;(getActivity(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1, DummyContent.ITEMS));
    }

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Restore the previously serialized activated item position.
    if (savedInstanceState != null
            &amp;&amp; savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
        setActivatedPosition(savedInstanceState
                .getInt(STATE_ACTIVATED_POSITION));
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // Activities containing this fragment must implement its callbacks.
    if (!(activity instanceof Callbacks)) {
        throw new IllegalStateException(
                &quot;Activity must implement fragment's callbacks.&quot;);
    }

    mCallbacks = (Callbacks) activity;
}

@Override
public void onDetach() {
    super.onDetach();

    // Reset the active callbacks interface to the dummy implementation.
    mCallbacks = sDummyCallbacks;
}

@Override
public void onListItemClick(ListView listView, View view, int position,
        long id) {
    super.onListItemClick(listView, view, position, id);

    // Notify the active callbacks interface (the activity, if the
    // fragment is attached to one) that an item has been selected.
    mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mActivatedPosition != ListView.INVALID_POSITION) {
        // Serialize and persist the activated item position.
        outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
    }
}

/**
 * Turns on activate-on-click mode. When this mode is on, list items will be
 * given the 'activated' state when touched.
 */
public void setActivateOnItemClick(boolean activateOnItemClick) {
    // When setting CHOICE_MODE_SINGLE, ListView will automatically
    // give items the 'activated' state when touched.
    getListView().setChoiceMode(
            activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
                    : ListView.CHOICE_MODE_NONE);
}

private void setActivatedPosition(int position) {
    if (position == ListView.INVALID_POSITION) {
        getListView().setItemChecked(mActivatedPosition, false);
    } else {
        getListView().setItemChecked(position, true);
    }

    mActivatedPosition = position;
}

}

DUMMY CONTENT FÜR DIE LISTVIEW

package com.example.test1.dummy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p>
* TODO: Replace all uses of this class before publishing your app.
*/
public class DummyContent {

/**
 * An array of sample (dummy) items.
 */
public static List&lt;DummyItem&gt; ITEMS = new ArrayList&lt;DummyItem&gt;();

/**
 * A map of sample (dummy) items, by ID.
 */
public static Map&lt;String, DummyItem&gt; ITEM_MAP = new HashMap&lt;String, DummyItem&gt;();

static {
    // Add items.
    addItem(new DummyItem(&quot;1&quot;, &quot;Thema1&quot;));
    addItem(new DummyItem(&quot;2&quot;, &quot;Thema2&quot;));
    addItem(new DummyItem(&quot;3&quot;, &quot;Thema3&quot;));
    addItem(new DummyItem(&quot;4&quot;, &quot;Thema4&quot;));
    addItem(new DummyItem(&quot;5&quot;, &quot;Thema5&quot;));
    addItem(new DummyItem(&quot;6&quot;, &quot;Thema6&quot;));
    addItem(new DummyItem(&quot;7&quot;, &quot;Thema7&quot;));
    addItem(new DummyItem(&quot;8&quot;, &quot;Thema8&quot;));
    addItem(new DummyItem(&quot;9&quot;, &quot;Thema9&quot;));
    addItem(new DummyItem(&quot;10&quot;,&quot;Thema10&quot;));
}

private static void addItem(DummyItem item) {
    ITEMS.add(item);
    ITEM_MAP.put(item.id, item);
}

/**
 * A dummy item representing a piece of content.
 */
public static class DummyItem {
    public String id;
    public String content;

    public DummyItem(String id, String content) {
        this.id = id;
        this.content = content;
    }

    @Override
    public String toString() {
        return content;
    }
}

}

IMAGE ADAPTER (INTEGER ARRAY FÜR DIE BILDER)

package com.example.test1.dummy;

import com.example.test1.R;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter{

private Context mContext;

public ImageAdapter(Context c){
    mContext = c;
}

@Override
public int getCount() {
    return mThumbIds.length;
}

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

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

@Override
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {  // if it's not recycled, initialize some attributes
        imageView = new ImageView(mContext);
        imageView.setLayoutParams(new GridView.LayoutParams(170, 170));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(10, 10, 10, 10);
    } else {
        imageView = (ImageView) convertView;
    }

    //hier kommt eine if-Abfrage, welche Themen angetippt wurden
    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

    //hier kommen 10 Arrays f&uuml;r die Themen, gef&uuml;llt mit den Aufgaben
private Integer[] mThumbIds = {
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7
};

}

FRAGMENT FÜR DIE GRIDVIEW

package com.example.test1;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.test1.dummy.DummyContent;
import com.example.test1.dummy.ImageAdapter;

/**
* A fragment representing a single Item detail screen. This fragment is either
* contained in a {@link ItemListActivity} in two-pane mode (on tablets) or a
* {@link ItemDetailActivity} on handsets.
/
public class ItemDetailFragment extends Fragment {
/
*
* The fragment argument representing the item ID that this fragment
* represents.
*/
//public static final String ARG_ITEM_ID = "item_id";

/**
 * The dummy content this fragment is presenting.
 */
private DummyContent.DummyItem mItem;

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ItemDetailFragment() {
}

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

    /*if (getArguments().containsKey(ARG_ITEM_ID)) {
        // Load the dummy content specified by the fragment
        // arguments. In a real-world scenario, use a Loader
        // to load content from a content provider.
        mItem = DummyContent.ITEM_MAP.get(getArguments().getString(
                ARG_ITEM_ID));
    }*/
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_item_detail,
            container, false);

    GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
    gridView.setAdapter(new ImageAdapter(rootView.getContext()));

    ////if-Abfrage nach DummyContent.DummyItem mItem um zu &uuml;berpr&uuml;fen welches Thema angetippt wurde!
    ////Abfrage nach id(String) oder content(String)

    // Show the dummy content as text in a TextView.
    /*if (mItem != null) {
        ((TextView) rootView.findViewById(R.id.item_detail))
                .setText(mItem.content);
    }*/

    return rootView;
}

}

Antworten
Pascal P.
  • Admin
  • Forum-Beiträge: 11.286

09.05.2014, 20:06:37 via Website

Ich finde das gerade irgendwie unübersichtlich.
Ich hätte es einfach so gemacht

Fragment: enthält eingenschaft für dein Array von Bilder das angezeigt werden soll.
Beim Anzeigen des Fragments holst du die Bilder aus dem Array und zeigst sie an.

Wenn du das Fragment dann erstellet mit new, dann musst du och die Richtige Array list zuweisen.

LG Pascal //It's not a bug, it's a feature. :) ;)

Antworten