使用片段加载包含 ListView 的布局文件,在此片段中初始化 ListView 适配器 class.But 参见注释

Use fragment to load a layout file which contains a ListView ,initialize the ListView adapter in this fragment class.But see noting

我使用NewsTitleFragmentclass加载布局文件news_title_frag.xml。这个文件只包含一个ListView。使用 findViewById 获取 ListView 实例,并设置适配器。但是什么也看不到

这是我的 NewsTitleFragment.class:

public class NewsTitleFragment extends Fragment{

    private ListView newsTitleListView;

    private List<News> newsList;

    private NewsAdapter adapter;


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        newsList = getNews();
        adapter = new NewsAdapter(context,R.layout.news_item,newsList);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_title_frag,container,false);
        newsTitleListView = (ListView) view.findViewById(R.id.news_title_list_view);
        newsTitleListView.setAdapter(adapter);

        return view;
    }

    private List<News> getNews(){
        List<News> newsList = new ArrayList<News>();
        News news1 = new News();
        news1.setContent("At this point in the campaign, even with the first votes fewer than 50 days away, national polls are not always the reliable predictors of where presidential nominating contests are heading. At this time four years ago, former congressman Newt Gingrich was tied with eventual nominee Mitt Romney on the Republican side. Eight years ago, former New York City mayor Rudy Giuliani led the GOP field, while Hillary Clinton held a wide lead over then-Sen. Barack Obama among Democrats. Giuliani and Clinton eventually lost.");
        news1.setTitle("In face of criticism, Trump surges to his biggest lead over the GOP field");
        newsList.add(news1);

        News news2 = new News();
        news2.setContent("“This is an emerging humanitarian crisis. There is extreme suffering, and people are not being protected,” said Rae McGrath, country director for Turkey and North Syria for the American aid agency Mercy Corps, one of the largest providers of food aid in northern Syria. Since the Russian strikes began, the agency has been able to deliver only a fifth of the amount it normally provides, he said.");
        news2.setTitle("Russian airstrikes force a halt to aid in Syria, triggering a new crisis");
        newsList.add(news2);

        News news3 = new News();
        news3.setTitle("For many at Liberty University, guns and God go hand in hand");
        news3.setContent("Many students, faculty members and administrators said they agreed with his views. Hundreds said they planned to take free classes from Liberty police on gun safety, a step toward obtaining a state permit to carry a concealed weapon. Among them were 21-year-old students Alvonta Tarrant and Dominique Richbur");
        newsList.add(news3);

        return newsList;
    }
}

这是我的 activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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: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.gaby.fragmentbestpractice.MainActivity"
        tools:showIn="@layout/activity_main">


        <fragment
            android:id="@+id/news_title_fragment"
            android:name="com.example.gaby.fragmentbestpractice.NewsTitleFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </LinearLayout>

这是我的 news_title_frag:

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

    <ListView
        android:id="@+id/news_title_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </ListView>

</LinearLayout>

这是我的 new_item.xml:

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

        <TextView
            android:id="@+id/news_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingBottom="15dp"
            android:paddingTop="15dp"
            android:textSize="18sp"
            android:ellipsize="end"
            />
    </LinearLayout>

这是News.class:

public class News {

    private String title;

    private String content;

    public String getContent() {
        return content;
    }

    public String getTitle() {
        return title;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}

这是我的适配器class NewsAdapter.class:

package com.example.gaby.fragmentbestpractice;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;


/**
 * Created by Gaby on 12/14/2015.
 */
public class NewsAdapter extends ArrayAdapter<News>{

    private int resourceId;

    public NewsAdapter(Context context, int textViewResourceId, List<News> objects) {
        super(context, textViewResourceId, objects);
        resourceId = textViewResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        News news = getItem(position);
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            view = LayoutInflater.from(getContext()).inflate(resourceId,null);
            viewHolder = new ViewHolder();
            viewHolder.textView = (TextView) view.findViewById(R.id.news_title);
            view.setTag(viewHolder);
        } else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.textView.setText(news.getTitle());
        return view;
    }

运行 结果如下:

应该有几个标题,怎么了?

尝试在你的适配器中添加这个功能class如果你没有(因为我在这里看不到)

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return objects.size();
}

您应该扩展 BaseAdapter 而不是 ArrayAdapter,在您使用 ArrayAdapter 的代码中,您的 new_item.xml 应该只包含这样的 TextView:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/news_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="15dp"
        android:paddingTop="15dp"
        android:textSize="18sp"
        android:ellipsize="end"
        />

您向我们展示的代码看起来是正确的,所以问题出在其他地方,即。使用您的主要 activity 布局,它应该加载您的片段,它应该看起来像:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.example.gaby.fragmentbestpractice.NewsTitleFragment"
        android:id="@+id/fragment2"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>

还要确保您的片段 xml 文件也正确,它应该类似于:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/news_title_list_view"/>

</RelativeLayout>

将以下行更改为 onCreateView 方法而不是 onAttach 。它会起作用:)

 newsList = getNews();
        adapter = new NewsAdapter(getActivity(),R.layout.new_item,newsList);