简体   繁体   中英

Do I need fragments and how to access them?

I am new to Android so my question may seem ridiculous but I cant figure it out.

I started creating an app some time ago and using 'Create new Android Activity' usually created a .java and .xml file for it, and everything worked. Now, after update when I use 'Create new Android Activity' it creates .java with class (which now extends ActionBarActivity and not Activity as before) and it adds a fragment_nameofactivity.xml + all things to make it work like internal class extending Fragment...

Now I used to do some ListView display on the page and without a fragment it all works great, but when fragment got introduced I can no longer findViewById(R.id.list_view) if its inside a fragment...

My question is do I need to place my whole functionality inside the class extending Fragment? I tried but it didn't work... Or do I still write all my functionality in the original class and then somehow access the listView in the fragment...

Here is the code:

public class PlayersActivity extends ActionBarActivity {

PlayerDataDatabaseAdapter playerDataHelper;

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

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    playerDataHelper = new PlayerDataDatabaseAdapter(this);
    playerDataHelper.open();

    displayPlayersList();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.players, 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();
    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 {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_players,
                container, false);
        return rootView;
    }
}

private void displayPlayersList() {
    Cursor cursor = playerDataHelper.getAllPlayers();

    String [] columns = playerDataHelper.columnsToBind();

    int [] to = new int[] {
            R.id.player_name,
    };

    SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter(this, R.layout.fragment_player_details, cursor, columns, to, 0);

    ListView listView = (ListView) findViewById(R.id.players_list);
    listView.setAdapter(dataAdapter);

    listView.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
            Cursor cursor = (Cursor) listView.getItemAtPosition(position);

            int player_id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));

            Intent intent = new Intent(PlayersActivity.this, EditPlayerActivity.class);
            intent.putExtra("PlayerId", player_id);
            startActivity(intent);      
        }
    });
}   

public void addNewPlayer(View view) {
    Intent intent = new Intent(this, AddPlayerActivity.class);
    startActivity(intent);
}   
 }

Fragment_players.xml

<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="uk.co.eximage.soccermum.PlayersActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentTop="true"
    android:text="@string/players"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<Button
    android:id="@+id/button1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal = "true"
    android:layout_below="@+id/textView1"
    android:onClick="addNewPlayer"
    android:text="@string/add_player" />

<ListView
    android:id="@+id/players_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"
    >

</ListView>

</RelativeLayout>

activity_players.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="uk.co.eximage.soccermum.PlayersActivity"
tools:ignore="MergeRootFrame" />

Running this returns NullPointerException on the line that tries to get players_list:

 ListView listView = (ListView) findViewById(R.id.players_list);

after this listView is null.

What am I doing wrong?

And finally do I need fragments? Maybe I should just remove them and do it the 'old' way with one view per page?

You need to iniaitlize ListView in Fragment

ListView listView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_players,
            container, false);
listView = (ListView)rootView. findViewById(R.id.players_list);
playerDataHelper = new PlayerDataDatabaseAdapter(getActivity());
playerDataHelper.open();
displayPlayersList();

The ListView belongs to fragment_players.xml . Move all your code related to fragment in onCreateView .

Edit:

public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment() {
}

  ListView listView;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_players,
            container, false);
  listView = (ListView)rootView. findViewById(R.id.players_list);
  playerDataHelper = new PlayerDataDatabaseAdapter(getActivity());
  playerDataHelper.open();
  displayPlayersList();

    return rootView;
}
private void displayPlayersList() {
Cursor cursor = playerDataHelper.getAllPlayers();

String [] columns = playerDataHelper.columnsToBind();

int [] to = new int[] {
        R.id.player_name,
};

SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter(getActivity(), R.layout.fragment_player_details, cursor, columns, to, 0);
listView.setAdapter(dataAdapter);

listView.setOnItemClickListener(new OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> listView, View view, int position, long id)       {
        Cursor cursor = (Cursor) listView.getItemAtPosition(position);

        int player_id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));

        Intent intent = new Intent(getActivity(), EditPlayerActivity.class);
        intent.putExtra("PlayerId", player_id);
        startActivity(intent);      
    }
 });
} 
}

Fragments were introduced to better support the tablet form factor. If you don't plan to rearrange your display (ie. show list and detail view together), you don't need fragments and can go the old way.

您必须从片段rootView初始化Listview,或者必须全局声明ListView并在Fragment的onCreateView内初始化,或者必须全局声明View rootView并通过以下方式初始化listview

 ListView listView = (ListView) rootView .findViewById(R.id.players_list);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM