我需要片段以及如何访问它们吗?

时间:2014-04-04 08:27:35

标签: java android android-fragments android-listview

我是Android的新手,所以我的问题可能看起来很荒谬,但我无法弄明白。

我前段时间开始创建应用并使用“创建新Android活动”#39;通常为它创建一个.java和.xml文件,一切正常。现在,更新后我使用“创建新Android活动”#39;它创建.java与类(现在扩展ActionBarActivity而不是像以前一样扩展Activity)并且它添加了一个fragment_nameofactivity.xml +所有东西,使它像内部类扩展Fragment一样工作......

现在我曾经在页面上做了一些ListView显示而且没有片段它一切都很好用,但是当片段被引入时,我不能再找到ViewById(R.id.list_view),如果它在片段里面......

我的问题是我需要将整个功能放在扩展Fragment的类中吗?我试过但它没有工作......或者我仍然在原始类中编写所有功能,然后以某种方式访问​​片段中的listView ...

以下是代码:

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" />

运行它会在尝试获取players_list的行上返回NullPointerException:

 ListView listView = (ListView) findViewById(R.id.players_list);
此listView为空后

我做错了什么?

最后我需要片段吗?也许我应该删除它们,然后按照“旧”的标准去做。每页一个视图的方式?

3 个答案:

答案 0 :(得分:2)

您需要在Fragment中隐藏ListView

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();

ListView属于fragment_players.xml。在onCreateView中移动与片段相关的所有代码。

编辑:

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);      
    }
 });
} 
}

答案 1 :(得分:2)

引入碎片以更好地支持片剂形状因子。如果您不打算重新排列显示器(即同时显示列表和详细视图),则不需要片段,可以采用旧方法。

答案 2 :(得分:0)

您必须从片段rootView初始化Listview 您必须全局声明ListView并在片段的onCreateView内部初始化,或者必须全局声明View rootView并通过

初始化listview
 ListView listView = (ListView) rootView .findViewById(R.id.players_list);