2017-01-31 5 views
0

カスタムタブ/ビューページャ(フラグメント)を使用してRest API(JSONを解析する)を使用してリストビューデータを取り込み、Toastを配置してコードをデバッグしました。レイアウトはissue.Someoneだと思います(一度これが働いている、リフレッシュ機能をスワイプダウン実装します)案内してください: -リストビューのデータがViewPagerに埋め込まれていない

activity_main.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:layout_scrollFlags="scroll|enterAlways" 
      app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> 

     <android.support.design.widget.TabLayout 
      android:id="@+id/tabs" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      app:tabMode="fixed" 
      app:tabGravity="fill"/> 
    </android.support.design.widget.AppBarLayout> 

    <android.support.v4.view.ViewPager 
     android:id="@+id/viewpager" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior" /> 
</android.support.design.widget.CoordinatorLayout> 

activity_item1.xml

<?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/title" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textColor="@color/colorPrimaryDark" 
     android:textSize="16sp" 
     android:textStyle="bold" 
     /> 

    <ImageView 
     android:id="@+id/urlToImage" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_margin="10dip" 
     android:adjustViewBounds="true" 
     /> 

    <TextView 
     android:id="@+id/description" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textColor="#000000" 
     android:textSize="14sp" 
     /> 


    <Button 
     android:text="Read More.." 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/button_loadMore" 
     android:layout_below="@+id/url" 
     /> 

</LinearLayout> 

content_main.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:id="@+id/content_main" 
    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" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.example.amk.myfirstapplication.MainActivity" 
    tools:showIn="@layout/activity_main"> 

    <ListView 
     android:id="@+id/text_json" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textColor="@android:color/holo_blue_dark" 
     android:textColorHighlight="@android:color/primary_text_dark" 
     android:layout_centerVertical="true" 
     android:layout_alignParentEnd="true" 
     android:cacheColorHint="#00000000" 
     android:textSize="14sp" /> 


</RelativeLayout> 

MainActivity.java

public class MainActivity extends AppCompatActivity { 

    private ViewPager viewPager; 
    private Toolbar toolbar; 
    private TabLayout tabLayout; 

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

     setContentView(R.layout.activity_main); 

     toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

     viewPager = (ViewPager) findViewById(R.id.viewpager); 
     setupViewPager(viewPager); 

     tabLayout = (TabLayout) findViewById(R.id.tabs); 
     tabLayout.setupWithViewPager(viewPager); 

    } 

    private void setupViewPager(ViewPager viewPager) { 
     TabsPagerAdapter adapter = new TabsPagerAdapter(getSupportFragmentManager()); 
     adapter.addFragment(new Item1(),"Item1"); 
     adapter.addFragment(new Item2(),"Item2"); 
     viewPager.setAdapter(adapter); 
    } 


} 

TabsPagerAdapter.java

public class TabsPagerAdapter extends FragmentPagerAdapter { 

    private final List<Fragment> mFragmentList = new ArrayList<>(); 
    private final List<String> mFragmentTitleList = new ArrayList<>(); 

    public TabsPagerAdapter(FragmentManager manager) { 
     super(manager); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     return mFragmentList.get(position); 
    } 

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

    public void addFragment(Fragment fragment, String title) { 
     mFragmentList.add(fragment); 
     mFragmentTitleList.add(title); 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     return mFragmentTitleList.get(position); 
    } 
} 

Item1.java

public class Item1 extends Fragment implements SwipeRefreshLayout.OnRefreshListener { 


    ArrayList<HashMap<String, String>> newsList = new ArrayList<>(); 

    //private SwipeRefreshLayout swipeRefreshLayout; 

    AssetManager assetManager; 
    InputStream inputStream = null; 

    InputStreamReader isr = null; 
    BufferedReader input = null; 
    String line=null; 
    ArrayList<String> list = new ArrayList<>(); 

    private Context myContext; 

    public Item1(){ } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 


     super.onCreate(savedInstanceState); 

    } 

    @Override 
    public void onRefresh() { 

     Toast.makeText(this.getActivity(), "Calling onRefresh", Toast.LENGTH_SHORT).show(); 
     try { 
      assetManager = this.getActivity().getAssets(); 
      inputStream = assetManager.open("RestEndPoints.txt"); 
      isr = new InputStreamReader(inputStream); 
      input= new BufferedReader(isr); 

      while ((line = input.readLine()) != null) { 
       list.add(line); 
      } 
      Collections.shuffle(list); 
      Toast.makeText(this.getActivity(), "List"+list.size(), Toast.LENGTH_SHORT).show(); 
      for (String url : list) { 
       new Item1.MyAsyncTask().execute(url); 
      } 
     }catch (Exception e) 
     { 
      Toast.makeText(this.getActivity(), "Got exception", Toast.LENGTH_SHORT).show(); 
      e.getMessage(); 
     } 

    } 

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

     onRefresh(); 


     return inflater.inflate(R.layout.activity_item1, container,false); 
    } 


    class MyAsyncTask extends AsyncTask<String, Void, String> { 



     @Override 
     protected String doInBackground(String... urls) { 
      //swipeRefreshLayout.setRefreshing(true); 
      return RestService.doGet(urls[0]); 
     } 

     @Override 
     protected void onPostExecute(String result) { 

      if(RetainData.reuseArray == null) 
       RetainData.reuseArray = new ArrayList<>(); 
      Toast.makeText(getContext(), "Entering Json loop", Toast.LENGTH_SHORT).show(); 

      try { 

       JSONObject json = new JSONObject(result); 
       JSONArray articles = (JSONArray) json.get("articles"); 

       for (int i=0;i< articles.length();i++) 
       { 
        JSONObject c = (JSONObject) articles.get(i); 
        String author = c.getString("author"); 
        String title = c.getString("title"); 
        String description = c.getString("description"); 
        String url = c.getString("url"); 
        String urlToImage = c.getString("urlToImage"); 
        String publishedAt = c.getString("publishedAt"); 

        HashMap<String, String> hm = new HashMap<>(); 
        hm.put("author",author); 
        hm.put("title",title); 
        hm.put("description",description); 
        hm.put("url",url); 
        hm.put("urlToImage",urlToImage); 
        hm.put("publishedAt",publishedAt); 

        newsList.add(hm); 

        RetainData.reuseArray.add(new com.example.amk.myfirstapplication.ItemList(author, title, description, url, urlToImage, publishedAt)); 
        Toast.makeText(getContext(), "Size:"+newsList.size() , Toast.LENGTH_LONG).show(); 
       } 


       com.example.amk.myfirstapplication.CustomAdapter adapter = new com.example.amk.myfirstapplication.CustomAdapter(myContext,RetainData.reuseArray); 

       ListView listView = (ListView) getView().findViewById(R.id.text_json); 

       Toast.makeText(getContext(), ""+RetainData.reuseArray.size(), Toast.LENGTH_SHORT).show(); 
       listView.setAdapter(adapter); 


      } 
      catch(Exception e) 
      { 
       e.printStackTrace(); 
      } 


     } 
    } 
} 

CustomAdapter.java

public class CustomAdapter extends ArrayAdapter<com.example.amk.myfirstapplication.ItemList>{ 

    private Context mContext; 

    public CustomAdapter(Context context, List<ItemList> items) { 
     super(context, 0, items); 
     mContext = context; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     // Get the data item for this position 
     final com.example.amk.myfirstapplication.ItemList item = getItem(position); 
     // Check if an existing view is being reused, otherwise inflate the view 
     if (convertView == null) { 
      convertView = LayoutInflater.from(getContext()).inflate(R.layout.content_main, parent, false); 
     } 
     // Lookup view for data population 
     //TextView authorName = (TextView) convertView.findViewById(R.id.author); 
     TextView titleName = (TextView) convertView.findViewById(R.id.title); 
     TextView descriptionName = (TextView) convertView.findViewById(R.id.description); 
     ImageView urlToImageName = (ImageView) convertView.findViewById(urlToImage); 

     Button readMore = (Button) convertView.findViewById(R.id.button_loadMore); 
     //TextView publishedAtName = (TextView) convertView.findViewById(R.id.publishedAt); 

     // Populate the data into the template view using the data object 
     //authorName.setText(item.author); 
     titleName.setText(item.title); 
     descriptionName.setText(item.description); 
     readMore.setTag(item.url); 

     readMore.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       //Toast.makeText(mContext, (String)v.getTag(), Toast.LENGTH_SHORT).show(); 
       CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); 
       /*builder.setCloseButtonIcon(BitmapFactory.decodeResource(
         getResources(), R.drawable.ic_arrow_back));*/ 
       CustomTabsIntent customTabsIntent = builder.build(); 

       customTabsIntent.launchUrl(mContext, Uri.parse(item.url)); 
      } 
     }); 


     Glide.with(convertView.getContext()) 
       .load(item.urlToImage) 
       .thumbnail(0.5f) 
       .override(600,200) 
       .placeholder(R.drawable.android_logo) 
       .crossFade() 
       .into(urlToImageName); 

     return convertView; 

    } 

} 

答えて

0
activity_main.xml 

    <?xml version="1.0" encoding="utf-8"?> 
    <android.support.design.widget.CoordinatorLayout 
    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:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:context="com.example.vimesh.myapplication.MainActivity"> 

    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 
     <android.support.design.widget.TabLayout 
      android:id="@+id/tabs" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      app:tabMode="fixed" 
      app:tabGravity="fill"/> 

    </android.support.design.widget.AppBarLayout> 

    <include layout="@layout/content_main" /> 

    </android.support.design.widget.CoordinatorLayout> 

content_main.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:id="@+id/content_main" 
    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" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="com.example.vimesh.myapplication.MainActivity" 
    tools:showIn="@layout/activity_main"> 

    <android.support.v4.view.ViewPager 
     android:id="@+id/pager" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 
    </android.support.v4.view.ViewPager> 
    </RelativeLayout> 

first_fragment.xmlは

<ListView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/listview"/> 

ViewPagerは、ユーザが左または全く新しい参照する 右スワイプすることを可能にするウィジェットでありますViewPager がスクロールできる画面は、実際にはFrです。あなたの例ではあなたは ViewPagerの下にlistviewを追加しましたので、各フラグメントを呼び出すときに はlistview.Soをオーバーライドします。 フラグメントのリストビューを追加します。content_main.xmlファイルのビューページャーを追加します。それは動作します

+0

申し訳ありませんが、私の完全なコードを以下に掲載しました: - – Addy

0

これは古いかもしれないが、誰かを助けるかもしれない。 リストデータを含むマルチタブアプリを構築する際には、以下のことを確認する必要があります。あなたのコードは完全ではありませんが、ここですべてのことを説明してください。

最初:viewpagerのタブを投入すると、リストデータとは異なり、あなたが

adapter.addFragment(new Item2(),"Item2"); 

をそれを行っている

:取り込むデータが断片的にではなくmainactivityで行われます。 Item2.javaに行くと、このようなあなたのコードを追加します。

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

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
//your code here 
    } 

あなたのアプリを実行している間、あなたが最初のIDを取得していることを確認し、リストを作成すると、最後に、アダプタを使用してリストビューをバインドします。ほとんどの人はそれを忘れる

フラグメントでは、最後のコードとしてビューを返す必要があります。それ以外の場合は、アプリケーションがクラッシュします。

関連する問題