2016-10-14 6 views
0

Retrofit에서 2 개의 개체에 매핑되는 내용으로 GridView을 채우려고합니다. 저는 Retrofit 부분을 이미 작동 시켰으며, 필요한 데이터를 성공적으로 수신하고 있습니다.이 GridView를 채우기 위해 사용자 지정 어댑터가 필요합니까? 그렇다면 어떻게 만들 수 있습니까?

그러나 데이터 유형이 혼합되어 있기 때문에이 경우에는 GridView을 어떻게 채울 지 모르겠지만 사용자 지정 어댑터가 필요하기 때문에 거의 확실하다고 확신합니다. 나는 ArrayAdapter을 기반으로 맞춤형 어댑터를 만들려고했으나이를 구현하는 방법을 모르며 온라인 검색을 시도했지만 여전히 잘 이해하지 못합니다.

GridView (그리고 내가 필요한 모든 속성을 가지고 잘 모르겠어요 솔직히 말해서) 순간에 아주 기본적인,하지만 여기있다 :

<GridView 
     android:id="@+id/gv_content" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:paddingBottom="@dimen/activity_vertical_margin" 
     android:paddingLeft="@dimen/activity_horizontal_margin" 
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin"> 

</GridView> 

데이터를 내 클래스 매핑되는 개조 그들에게 다음과 같이 :

NewsAPI.java :

public class NewsAPI { 
    String status; 
    String source; 
    ArrayList<Articles> articles; 

    public NewsAPI(String status, String source, ArrayList<Articles> articles) { 
     this.status = status; 
     this.source = source; 
     this.articles = articles; 
    } 
} 

Articles.java을 :

public class Articles { 
    String title; 
    String description; 

    public Articles(String title, String description) { 
     this.title = title; 
     this.description = description; 
    } 
} 

미리 감사드립니다.

편집 : 다음은 Retrofit을 통해 구문 분석하기 전의 원래 JSON 데이터의 예입니다.

{ 
"status": "ok", 
"source": "techcrunch", 
"sortBy": "top", 
-"articles": [ 
-{ 
"author": "Darrell Etherington", 
"title": "Six new Sun and Moon Pokémon evolutions revealed", 
"description": "Pokémon Sun and Moon's release for 3DS rapidly approaches, and the Pokémon Company is unveiling eight new Pokémon unique to the new games, including six..", 
"url": "http://social.techcrunch.com/2016/10/14/six-new-sun-and-moon-pokemon-evolutions-revealed/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/poke-compressor.gif?w=680&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-14T14:29:12Z" 
}, 
-{ 
"author": "Brian Heater", 
"title": "That Nike-branded Apple Watch arrives October 28", 
"description": "Maybe you’ve been waiting for the Nike+ version to arrive before running out to buy the Apple Watch Series 2. Because, you know, life is a marathon, not a..", 
"url": "http://social.techcrunch.com/2016/10/14/nike-apple-watch/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/09/img_8919.jpg?w=764&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-14T13:33:25Z" 
}, 
-{ 
"author": "Darrell Etherington", 
"title": "Iron Man offers to voice Mark Zuckerberg’s real-life Jarvis AI", 
"description": "Facebook CEO Mark Zuckerberg sets an ambitious goal every year for himself, and this year it was to create an AI assistant for his home, modelled in part on..", 
"url": "http://social.techcrunch.com/2016/10/14/iron-man-offers-to-voice-mark-zuckerbergs-real-life-jarvis-ai/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/91kwg8.jpg?w=764&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-14T12:06:22Z" 
}, 
-{ 
"author": "Natasha Lomas", 
"title": "Instagram now has an app for Windows 10 tablets", 
"description": "Instagram has expanded its app availability to users of tablets running Microsoft's Windows 10. The Facebook-owned, visual content social sharing platform..", 
"url": "http://social.techcrunch.com/2016/10/14/instagram-now-has-an-app-for-windows-10-tablets/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/screen-shot-2016-10-14-at-12-49-56-pm.png?w=622&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-14T11:10:47Z" 
}, 
-{ 
"author": "Ingrid Lunden", 
"title": "Spotify co-founder Martin Lorentzon steps down as chairman, CEO Daniel Ek steps up", 
"description": "A changing of the guard is underway at Spotify, the streaming music service with 40 million paying users and over 100 million overall that competes with the..", 
"url": "http://social.techcrunch.com/2016/10/14/spotify-co-founder-martin-lorentzon-steps-down-as-chairman-ceo-daniel-ek-steps-up/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2014/05/screen-shot-2014-05-21-at-11-19-55-am.png?w=764&amp;h=364&amp;crop=1", 
"publishedAt": "2016-10-14T10:32:48Z" 
}, 
-{ 
"author": "Natasha Lomas", 
"title": "Softbank and Saudi Arabia’s PIF planning $100BN tech fund", 
"description": "Softbank has announced it is creating a new global tech investment fund, seeded with $25 billion of its own money. The fund, which will be London, UK based --..", 
"url": "http://social.techcrunch.com/2016/10/14/softbank-and-saudi-arabias-pif-planning-100bn-tech-fund/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2015/01/softbank-img.jpg?w=764&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-14T08:33:08Z" 
}, 
-{ 
"author": "Sarah Buhr", 
"title": "GM’s car sharing company Maven hits the streets of San Francisco", 
"description": "Maven, a car sharing company out of General Motors, is driving its way into San Francisco today. The announcement made late Thursday evening is one part of a..", 
"url": "http://social.techcrunch.com/2016/10/13/gms-one-way-ride-startup-maven-hits-the-streets-of-san-francisco/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/01/gmmaven02.jpg?w=764&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-14T04:00:54Z" 
}, 
-{ 
"author": "Khaled \"Tito\" Hamze", 
"title": "Crunch Report | Soylent Bars Are Getting Recalled", 
"description": "Hyperloop One raises $50 million from DP World Group of Dubai, Soylent Bars are being recalled, Silicon Valley elites donate to controversial Prop Q,..", 
"url": "http://social.techcrunch.com/2016/10/13/crunch-report-soylent-bars-are-getting-recalled/", 
"urlToImage": "https://img.vidible.tv/prod/2016-10/13/580007b7869ea9143336a6ec_o_U_v1.jpg?w=764&#038;h=400", 
"publishedAt": "2016-10-14T03:00:40Z" 
}, 
-{ 
"author": "Rudina Seseri", 
"title": "The AI disruption wave", 
"description": "Information technology evolves through disruption waves. First the computer, then the web and eventually social networks and smartphones all had the power to..", 
"url": "http://social.techcrunch.com/2016/10/13/the-ai-disruption-wave/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/gettyimages-4964795042560x-80.jpg?w=764&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-14T03:00:39Z" 
}, 
-{ 
"author": "John Mannes", 
"title": "Returnly raises $3.2M to immediately refund your money after an online return", 
"description": "Returning a product you bought online is inherently a statement of dislike, but smart retailers are quickly learning that they're far better off if they..", 
"url": "http://social.techcrunch.com/2016/10/13/returnly-raises-3-2m-to-immediately-refund-your-money-after-an-online-return/", 
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2016/10/gettyimages-495813985.jpg?w=764&amp;h=400&amp;crop=1", 
"publishedAt": "2016-10-13T23:45:18Z" 
} 
] 
} 
+0

다음을 사용하여 두 개의 서로 다른 API에서 기사를로드 희망 NewsAPI 내부에 추가하고 병합하여 GridView의 동일한 레벨에서 함께 보여주고 싶습니다. 나는 그것을 올바르게 받았 느냐? –

+0

@MohsenMirhoseiniArgi 아니요, 동일한 API에서 JSON 데이터를로드하고 있지만 기사 자체는 NewsAPI 객체 내부의 배열입니다. 내 질문에 JSON 데이터 예제를 추가했습니다. – KaiZ

답변

0

맞춤 어댑터가 필요하지 않으며 매우 간단합니다!

NewsAPI 내에 여분의 물건으로 혼동하지 마십시오. 기사를 그리드에 표시하면 기사 ArrayList를 어댑터에 전달하는 것으로 충분합니다.

나는 GridLayoutManagerRecyclerView을 사용하여 선호 :

your_activity.xml :

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

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/gv_content" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 
</LinearLayout> 

item_article.xml :이처럼 Adapter를 정의 할 필요가

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

    <TextView 
     android:id="@+id/author" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <!--other elements--> 

</LinearLayout> 

를 :

RecyclerViewAdapter.java :

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ArticleViewHolder> { 
    ArrayList<Articles> articles; 

    public RecyclerViewAdapter(ArrayList<Articles> articles) { 
     this.articles = articles; 
    } 

    @Override 
    public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View view = LayoutInflater.from(parent.getContext()) 
       .inflate(R.layout.item_article, parent, false); 
     return new ArticleViewHolder(view); 
    } 

    @Override 
    public void onBindViewHolder(ArticleViewHolder holder, int position) { 
     final Articles article = articles.get(position); 

     holder.setArticles(article); 
     holder.bindData(); 
    } 

    @Override 
    public int getItemCount() { 
     return articles.size(); 
    } 

    @Override 
    public int getItemViewType(int position) { 
     return super.getItemViewType(position); 
    } 

    public class ArticleViewHolder extends RecyclerView.ViewHolder { 

     public final View view; 
     Articles articles; 

     public TextView author; 

     public ArticleViewHolder(View view) { 
      super(view); 
      this.view = view; 

      author = (TextView) view.findViewById(R.id.author); 
      // find other UI elements! 
     } 

     public void setArticles(Articles articles) { 
      this.articles = articles; 
     } 

     public void bindData() { 
      author.setText(articles.getTitle()); 
     } 
    } 

} 

하고이 같은 설정 RecyclerView에 있습니다

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.gv_content); 

GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2); 
recyclerView.setLayoutManager(gridLayoutManager); 

recyclerView.setAdapter(new RecyclerViewAdapter(newsAPI.getArticles())); 

나는 그것이 도움이 :)