列表视图数据未在ViewPager中填充

时间:2017-01-31 16:24:29

标签: android android-layout android-fragments

我使用Rest API(解析JSON)填充列表视图数据,通过使用自定义选项卡/ View Tor with Fragments,我通过放入Toast调试代码,数据填充在列表中,但我猜布局是问题。请指导(一旦这个工作,将实现向下刷新功能): -

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;

    }

}

2 个答案:

答案 0 :(得分: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        允许用户滚动到真正的Fragment.in你的例子        在ViewPager下添加了listview,所以当你调用每个片段时         将覆盖listview.So在其中一个中添加列表视图        content_main.xml文件中的fragment..add viewpager ....希望它能正常工作

答案 1 :(得分:0)

这可能是旧的,但它可能对某人有所帮助。 在使用列表数据构建多标签应用程序时,这些是确保您遵循的内容。你的代码不完整,但在这里解释一切。

首先:填充viewpager上的标签与列表数据不同,你做得很好

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

second :填充数据将在片段中完成,而不是在mainactivity中完成。转到Item2.java并添加如下代码:

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

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

在运行您的应用时,请确保先获取ID,填充列表,最后将listview与适配器绑定。大多数人都忘记了

theList.setAdapter(yourAdapter);

在片段中,您需要将视图作为最后一段代码返回,否则您的应用程序将崩溃。