ListView в активности с вкладками не отображается

Я создал вкладку в Android Studio, выбрав ее в диалоговом окне "Новая активность".

Количество вкладок не является фиксированным, но оно читается из файла, так что имеется случайное количество вкладок. Для этой цели я использовал FragmentStatePagerAdapter.

В этом упражнении я хочу показать просмотр списка, заполняемый по-разному для каждой вкладки, но проблема в том, что просмотр списка не отображается.

Как вы можете видеть ниже, это класс java, где я выполняю операции на вкладках.

public class TournamentActivity extends AppCompatActivity {

private int returnT = 0, goingT = 0;

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tournament);

    Intent intent = this.getIntent();

    String committee = intent.getStringExtra(TournamentsAdapter.EXTRA_COMMITTEE);
    String tournament = intent.getStringExtra(TournamentsAdapter.EXTRA_TOURNAMENT);
    String roundName = intent.getStringExtra(TournamentsAdapter.EXTRA_ROUNDNAME);
    int roundId = intent.getExtras().getInt("EXTRA_ROUNDID");
    int roundAr = intent.getExtras().getInt("EXTRA_ROUNDAR");
    int matchDay = intent.getExtras().getInt("EXTRA_MATCHDAY");
    int roundStage = intent.getExtras().getInt("EXTRA_ROUNDSTAGE");

    new GetDataFromURL(this, "tournament.html").execute("http://www.fip.it/AjaxGetDataCampionato.asp?com=" + committee + "&camp=" + tournament + "&fase=" + roundStage + "&girone=" + roundId + "&ar=" + roundAr + "&turno=" + matchDay);

    //parse del file per vedere titolo e quante schede fare (numero di giornate del campionato)

    try{
        FileReader fr = new FileReader(getFilesDir() + "/ImportData/tournament.html");
        BufferedReader br = new BufferedReader(fr);

        String line;

        while((line = br.readLine())!= null){
            if(line.contains("tableTopBkg")){
                while((line = br.readLine())!= null){
                    Pattern pattern = Pattern.compile(">(.+?)</div>");
                    Matcher matcher = pattern.matcher(line);
                    while (matcher.find()){
                        String s = matcher.group(1);
                        s = s.substring(s.lastIndexOf(">") + 1);
                        returnT = Integer.parseInt(s);
                    }

                    if(line.equals("</tr>") && goingT == 0){
                        goingT += returnT;
                    }
                    else if(line.equals("</tr>")){
                        break;
                    }

                }

            }
        }

        System.out.println(returnT);

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


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    if(roundAr == 1)
        mViewPager.setCurrentItem(matchDay - 1);
    else if(roundAr == 0)
        mViewPager.setCurrentItem((matchDay + goingT) - 1);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_tournament, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }


    // +++++ QUI SI POPOLANO LE TABS +++++
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_tournament, container, false);

        TextView textView = (TextView) rootView.findViewById(R.id.section_label);

        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ListView listViewGames = (ListView) view.findViewById(R.id.listViewGames);
        GamesAdapter adapter = new GamesAdapter(getActivity(), android.R.layout.simple_list_item_1);

        listViewGames.setAdapter(adapter);
    }

    /*
    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);

        GamesAdapter adapter = new GamesAdapter(getContext(), R.layout.activity_tournament);

        listViewGames.setAdapter(adapter);
    }*/
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show N total pages.
        return goingT + returnT;
    }
}
}

в onViewCreated метод я получаю ссылку на просмотр списка, а затем создать свой собственный адаптер. Впоследствии с listViewGames.setAdapter(adapter); Я установил адаптер.

В этот момент, когда onViewCreated называется, setAdapter метод не вызывает getView в адаптере. Я также попытался установить адаптер в onCreateView метод, но он все равно не работает.

Это класс адаптера:

public class GamesAdapter extends ArrayAdapter{

private Context context;

public GamesAdapter(Context context, int resource) {
    super(context, resource);
    this.context = context;
}

@Override
public View getView(int position, View convertView, ViewGroup parent){

    LayoutInflater inflater = LayoutInflater.from(context);
    convertView = inflater.inflate(R.layout.fragment_games, null);

    ImageView imageViewStatus = (ImageView) convertView.findViewById(R.id.imageViewStatus);
    ImageView imageViewTeamA = (ImageView) convertView.findViewById(R.id.imageViewTeamA);
    ImageView imageViewTeamB = (ImageView) convertView.findViewById(R.id.imageViewTeamB);

    TextView textViewGameId = (TextView) convertView.findViewById(R.id.textViewGameId);
    TextView textViewDateTime = (TextView) convertView.findViewById(R.id.textViewDateTime);
    TextView textViewTeamA = (TextView) convertView.findViewById(R.id.textViewTeamA);
    TextView textViewTeamB = (TextView) convertView.findViewById(R.id.textViewTeamB);
    TextView textViewScoreA = (TextView) convertView.findViewById(R.id.textViewScoreA);
    TextView textViewScoreB = (TextView) convertView.findViewById(R.id.textViewScoreB);

    FileReader fr = null;
    String gameId = "";

    try {

        fr = new FileReader(context.getFilesDir() + "/ImportData/tournament.html");

        BufferedReader br = new BufferedReader(fr);

        String line;
        int hops = 0;

        while((line = br.readLine())!= null){
            if(line.contains("<div class=\"risTrCode\">") && hops == position){

                Pattern pattern = Pattern.compile(">(.+?)</a></div>");
                Matcher matcher = pattern.matcher(line);

                gameId = matcher.group(1);
                System.out.println(gameId);

                hops++;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    textViewGameId.setText(gameId);

    return convertView;
}
}

0 ответов

Другие вопросы по тегам