2

我想让我的 Android 应用程序使用 Fragment Transactions,这样我就可以在各种 Fragment 之间切换显示它们的关联列表。在尝试仅转换为片段事务之前,我的应用程序运行良好。在我最初的 activity_main.xml 中,我删除了 android:name="com.birdsall.peter.chap.ChapterFragment",据我了解,您不能将 xml 定义的片段与片段事务一起使用。

1)我似乎无法正确使用 getSupportFragmentManager 中的 .add() 参数,即使使用来自工作示例的代码也是如此。
我还尝试使用较新版本的 FragmentTransactions 无济于事。
我什至使用 getSupportFragmentManager / FragmentTransactions 做了一个代码的工作示例,修改为使用我拥有的名称,它有效。然后我将该代码导入我的应用程序,但它在 .add() 语法上失败。我对 Android 开发有点陌生,无法确定我哪里出错了。

这是我的 FrameLayout 的主要 xml 布局

activity_main.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" >

 <FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_weight="1" />

 <fragment
      android:id="@+id/chapterfragments"

      android:layout_width="match_parent"
      android:layout_height="match_parent" />

 <!-- Removed this from above <fragment> block to enable Fragment Transaction

 android:name="com.birdsall.peter.chap.ChapterFragment"  -->              
 </LinearLayout>

这是 ChapterFragment ListView 的 xml 布局

章节片段.xml

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

<ListView android:id="@+id/chapterlist" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentLeft="true" />

</RelativeLayout>

这是列表 chapter_info.xml 的详细信息的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical" android:padding="6dip">


<TextView android:id="@+id/chapter1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView android:id="@+id/textViewLiteral" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/chapter1" android:text=" - "
android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView android:id="@+id/chaptertitle1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textViewLiteral" 
android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>

这是我修改过的MainActivity.java 。我离开了'setContentView(R.layout.activity_main);' 因为我认为我需要创建一个视图(即使它是空的)来添加片段视图。

package com.birdsall.peter.chap;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

public class MainActivity extends FragmentActivity implements       ChapterFragment.ChapterSelectedListener {



private static final String TAG = "Main_Activity";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "Starting ...");

setContentView(R.layout.activity_main);


if (findViewById(R.id.fragment_container) != null) {
  if (savedInstanceState != null) {
      return;
  }

  // Create an instance of ExampleFragment
  ChapterFragment firstFragment = new ChapterFragment();


  // Add the fragment to the 'fragment_container' FrameLayout
  getSupportFragmentManager().beginTransaction()
          **.add**(R.id.fragment_container, firstFragment).commit(); 


         Log.i(TAG, "Ending ..."); 
  }

}   ...

这是我的 ChapterFragment.java

package com.birdsall.peter.chap;

import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ChapterFragment extends Fragment implements     LoaderManager.LoaderCallbacks<Cursor> {
ChapterSelectedListener mCallback;
 // Container Activity must implement this interface
public interface ChapterSelectedListener {
    public void onChapterSelected(String position, int rowId);
}

 public SimpleCursorAdapter dataAdapter;
 private static final String TAG = "ChapterFragment";


 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) {
     View listview = inflater.inflate(R.layout.activity_main,null);
     ListView mList =(ListView)listview.findViewById(R.id.chapterlist);
      // The desired columns to be bound
      String[] columns = new String[] {
        TDAdb.COL_CHAPTER,
        TDAdb.COL_CHAPTERTITLE};


      // the XML defined views which the data will be bound to
      int[] to = new int[] { 
        R.id.chapter1,
        R.id.chaptertitle1,

      };

      // create an adapter from the SimpleCursorAdapter
      dataAdapter = new SimpleCursorAdapter(
        getActivity(), 
        R.layout.chapter_info, 
        null, 
        columns, 
        to,
        0);
      mList.setAdapter(dataAdapter);
      //Ensures a loader is initialized and active.
      getLoaderManager().initLoader(0, null, this);
     return listview;

 }
 @Override
 public void onStart() {
  super.onStart();
  Log.i(TAG, " onStart");
  displayListView(); 
  Log.i(TAG, " end of onStart");
 } 
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (ChapterSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement ChapterSelectedListener");
        }
    }

 @Override
public void onResume() {
  super.onResume();
  //Starts a new or restarts an existing Loader in this manager
  Log.i(TAG, " onResume");
  getLoaderManager().restartLoader(0, null, this);
 }

 private void displayListView() {

     Log.i(TAG, " Starting displayListView");
  // The desired columns to be bound
  String[] columns = new String[] {
    TDAdb.COL_CHAPTER,
    TDAdb.COL_CHAPTERTITLE};


  // the XML defined views which the data will be bound to
  int[] to = new int[] { 
    R.id.chapter1,
    R.id.chaptertitle1,

  };

  // create an adapter from the SimpleCursorAdapter
  dataAdapter = new SimpleCursorAdapter(
    getActivity(), 
    R.layout.chapter_info, 
    null, 
    columns, 
    to,
    0);

  // get reference to the ListView
  ListView listView = (ListView) getView().findViewById(R.id.chapterlist);
  // Assign adapter to ListView
  listView.setAdapter(dataAdapter);
  //Ensures a loader is initialized and active.
  getLoaderManager().initLoader(0, null, this);


  listView.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> listView, View view, 
     int position, long id) {


    // Get the cursor, positioned to the corresponding row in the result set
    Cursor cursor = (Cursor) listView.getItemAtPosition(position);

    String chaptervalueselected = 
    cursor.getString(cursor.getColumnIndexOrThrow(TDAdb.COL_CHAPTER));

       mCallback.onChapterSelected(chaptervalueselected, position);
        Toast.makeText(getActivity(), "Chapter " + chaptervalueselected,     Toast.LENGTH_SHORT).show();

    // starts a new Intent to update/delete a Chapter
    // pass in row Id to create the Content URI for a single row
    //Intent chapterEdit = new Intent(getBaseContext(), ChapterEdit.class);
    //Bundle bundle = new Bundle();
    //bundle.putString("mode", "update");
    //bundle.putString("rowId", rowId);
    //chapterEdit.putExtras(bundle);
    //startActivity(chapterEdit);

   }
  });

 }

 // This is called when a new Loader needs to be created.
 @Override
 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
     Log.i(TAG, " onCreateLoader");
  String[] projection = { 
    TDAdb.KEY_ROWID,    
    TDAdb.COL_CHAPTER, 
    TDAdb.COL_CHAPTERTITLE}; 

  CursorLoader cursorLoader = new CursorLoader(getActivity(),
  TDAProvider.CONTENT_URI, projection, null, null, null);
  return cursorLoader;
 }

 @Override
 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
     Log.i(TAG, " ononLoadFinished");
  // Swap the new cursor in.  (The framework will take care of closing the
        // old cursor once we return.)
        dataAdapter.swapCursor(data);
 }

 @Override
 public void onLoaderReset(Loader<Cursor> loader) {
  // This is called when the last Cursor provided to onLoadFinished()
  // above is about to be closed.  We need to make sure we are no
  // longer using it.
     Log.i(TAG, " onLoaderReset");
  dataAdapter.swapCursor(null);
 } 


}
4

2 回答 2

4

如果您已经在使用您的add方法,则FragmentTransaction不得<fragment在布局中包含标签。如果你像这样离开你的主要活动 XML 怎么办:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
于 2013-05-24T15:09:11.847 回答
1

在 chapterFragment.java 中更改您的导入

import android.app.Fragment

import android.support.v4.app.Fragment
于 2015-05-29T01:33:47.313 回答