为什么我的自定义列表视图没有显示任何内容

时间:2017-12-01 06:07:44

标签: java android listview android-fragments

我正在制作一个列表视图,以显示代码中所有即将举行的竞赛。所以我创建了一个CodeforcesContest对象和一个包含ListView的片段。我希望有关比赛的所有信息都在ListView的一行中。比赛信息是比赛名称,比赛时间和另一个用于保存网站名称的字符串,它总是" Codeforces"。这是我到目前为止所拥有的。我是Java和android的新手。我搜索并找到了使用自定义类实现自定义列表视图的方法。但是,我的列表视图没有显示任何内容。我正在使用android studio 3.0

CodeforcesContest.java

package com.example.redwanul.cptracker;

/**
 * Created by redwanul on 12/1/17.
 */

public class CodeforcesContest {
    private String name;
    private String time;

    public CodeforcesContest(String name, String time) {
        this.name = name;
        this.time = time;
    }

    public String getName() {
        return name;
    }
    public String getTime() {
        return time;
    }
    public void setName(String name) { this.name = name; }
    public void setTime(String time) { this.time = time; }
}

单行的自定义布局。

row.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"
    android:weightSum="9">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/contest_name"
        android:layout_weight="3"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/contest_site"
        android:layout_weight="3"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:id="@+id/date_time"
        android:layout_weight="3"/>

</LinearLayout>

My Fragment类用于显示ListView。

FragmentUpcomingContest.java

package com.example.redwanul.cptracker;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragmentUpcomingContest.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragmentUpcomingContest#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentUpcomingContest extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragmentUpcomingContest.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentUpcomingContest newInstance(String param1, String param2) {
        FragmentUpcomingContest fragment = new FragmentUpcomingContest();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ArrayList <CodeforcesContest> arrayList = new ArrayList<>();
        CodeforcesContest[] contests;
        View myLayout = inflater.inflate(R.layout.fragment_fragment_upcoming_contest,container,false);

        ListView listView = myLayout.findViewById(R.id.listView);
        try {
            JSONArray jsonArray = new GetCodeforcesContestList().execute().get();
            for(int i = 0; i < jsonArray.length(); i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String _name = jsonObject.getString("name");
                String _phase = jsonObject.getString("phase");
                String _time = jsonObject.getString("startTimeSeconds");
                Log.d("Debug: name",_name);
                Log.d("Debug: phase",_phase);
                Log.d("Debug: Time",_time);
                if(_phase.equals(new String("BEFORE"))){
                    arrayList.add(new CodeforcesContest(_name,_time));
                }
            }

        }
        catch (Exception ex){
            ex.printStackTrace();
        }
        contests = new CodeforcesContest[arrayList.size()];

        for(int i = 0; i < arrayList.size(); i++){
            contests[i] = arrayList.get(i);
        }
        Log.d("Array Length: ", new Integer(arrayList.size()).toString());
        ContestAdapter mAdapter = new ContestAdapter(getContext(),R.layout.row,contests);
        listView.setAdapter(mAdapter);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_upcoming_contest, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

片段布局。 的 fragment_fragment_upcoming_contest

<FrameLayout 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"
    tools:context="com.example.redwanul.cptracker.FragmentUpcomingContest">

    <!-- TODO: Update blank fragment layout -->
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView">

    </ListView>

</FrameLayout>

我的自定义适配器用于显示列表。 的 ContestAdapter.java

package com.example.redwanul.cptracker;

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

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by redwanul on 12/1/17.
 */

public class ContestAdapter extends ArrayAdapter<CodeforcesContest> {
    Context context;
    int layourResourceId;
    private static LayoutInflater inflater = null;
    CodeforcesContest[] data = null;

    public ContestAdapter(Context context, int layoutResourceId, CodeforcesContest[] data){
        super(context,layoutResourceId,data);
        this.layourResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
        int ll = data.length;
        Log.d("Constructor",new Integer(data.length).toString());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if(vi == null)
            vi = inflater.inflate(R.layout.row,null);
        CodeforcesContest contest = data[position];
        Log.d("In Adapter",contest.getName());
        TextView contestName = (TextView)vi.findViewById(R.id.contest_name);
        TextView contestSite = (TextView)vi.findViewById(R.id.contest_site);
        TextView timeDate = (TextView)vi.findViewById(R.id.date_time);

        Date date = new Date(Integer.parseInt(contest.getTime()) * 1000);
        SimpleDateFormat formatter = new SimpleDateFormat("M/D/YYYY");
        String dateString = formatter.format(date);

        contestName.setText(contest.getName());
        contestSite.setText("Codeforces");
        timeDate.setText(dateString);
        return vi;
    }
}

1 个答案:

答案 0 :(得分:1)

  
      
  • 首先将 row.XML 高度更改为 android:layout_height="wrap_content"
  •   
<?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="wrap_content"
    android:orientation="vertical"
    android:weightSum="9">
  
      
  • 如果您返回错误的布局,则应返回myLayout而不是return inflater.inflate(R.layout.fragment_fragment_upcoming_contest,
  •   

使用此

return myLayout;

而不是

return inflater.inflate(R.layout.fragment_fragment_upcoming_contest,容器,false);