如何实现Android的碎片交易。新增语法错误 [英] How to implement Android Fragment Transaction .add syntax error

查看:190
本文介绍了如何实现Android的碎片交易。新增语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使我的Andr​​oid应用程序中使用的交易片段,让我可以
各个片段之间切换显示其相关的列表。我的应用程序
正常工作之前,尝试转换只是片段交易。在我最初activity_main.xml中,
我删除了android:NAME =com.birdsall.peter.chap.ChapterFragment,这是我的理解,你不能使用XML定义片段
与片段交易。

1)我似乎无法得到的。新增()内
getSupportFragmentManager它正确的参数,即使从一个工作示例code。结果
我也尝试使用FragmentTransactions的较新版本无济于事。结果
我甚至把code的工作示例使用getSupportFragmentManager / FragmentTransactions,
修改为使用我的名字,它的工作。然后我导入的code到我的应用程序
它失败的。新增()语法。我有点新的Andr​​oid开发,不能
找出我要去哪里错了。

下面是我对的FrameLayout

主要XML布局

activity_main.xml中

 <?XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent> <的FrameLayout
    机器人:ID =@ + ID / fragment_container
    机器人:layout_width =0dip
    机器人:layout_height =match_parent
    机器人:layout_weight =1/> <片段
      机器人:ID =@ + ID / chapterfragments      机器人:layout_width =match_parent
      机器人:layout_height =match_parent/> <! - 从上述&lt删除这一点;片断>阻塞,使交易片段 机器人:名字=com.birdsall.peter.chap.ChapterFragment - >
 < / LinearLayout中>

下面是ChapterFragment的ListView

的XML布局

chapterfragment.xml

 <?XML版本=1.0编码=UTF-8&GT?;
<的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent>< ListView的机器人:ID =@ + ID / chapterlist的android:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT机器人:layout_alignParentLeft =真/>< / RelativeLayout的>

下面是对列表的细节的布局
chapter_info.xml

 <?XML版本=1.0编码=UTF-8&GT?;
<的RelativeLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:layout_width =FILL_PARENT机器人:layout_height =WRAP_CONTENT
机器人:方向=垂直机器人:填充=6DIP>
< TextView的机器人:ID =@ + ID /第一章的android:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT机器人:layout_alignParentTop =真
机器人:textAppearance =:/>中的Andr​​oid ATTR / textAppearanceSmall?< TextView的机器人:ID =@ + ID / textViewLiteral的android:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT机器人:layout_alignParentTop =真
机器人:layout_toRightOf =@ + ID /第一章机器人:文本= -
机器人:textAppearance =:/>中的Andr​​oid ATTR / textAppearanceSmall?< TextView的机器人:ID =@ + ID / chaptertitle1的android:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT机器人:layout_alignParentTop =真
机器人:layout_toRightOf =@ + ID / textViewLiteral
机器人:textAppearance =:/>中的Andr​​oid ATTR / textAppearanceSmall?< / RelativeLayout的>

下面是在 MainActivity.java ,我已经修改。我离开的setContentView(R.layout.activity_main);'因为我认为我需要创建一个视图(即使它是空的)添加片段视图。

 包com.birdsall.peter.chap;进口android.os.Bundle;
进口android.support.v4.app.FragmentActivity;
进口android.util.Log;公共类MainActivity扩展FragmentActivity实现ChapterFragment.ChapterSelectedListener {私有静态最后弦乐TAG =Main_Activity;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
Log.i(TAG启动...);的setContentView(R.layout.activity_main);
如果(findViewById(R.id.fragment_container)!= NULL){
  如果(savedInstanceState!= NULL){
      返回;
  }  //创建ExampleFragment的一个实例
  ChapterFragment firstFragment =新ChapterFragment();
  //片段添加到fragment_container的FrameLayout
  getSupportFragmentManager()调用BeginTransaction()
          ** **加(R.id.fragment_container,firstFragment).commit();
         Log.i(TAG,结束...);
  }} ...

下面是我的ChapterFragment.java

 包com.birdsall.peter.chap;进口android.app.Activity;
进口android.app.Fragment;
进口android.app.LoaderManager;
进口android.content.CursorLoader;
进口android.content.Loader;
进口android.database.Cursor;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.AdapterView;
进口android.widget.AdapterView.OnItemClickListener;
进口android.widget.ListView;
进口android.widget.SimpleCursorAdapter;
进口android.widget.Toast;公共类ChapterFragment扩展片段实现LoaderManager.LoaderCallbacks<&光标GT; {
ChapterSelectedListener mCallback;
 //集装箱活动必须实现此接口
公共接口ChapterSelectedListener {
    公共无效onChapterSelected(字符串位置,诠释ROWID);
} 公共SimpleCursorAdapter DataAdapter的;
 私有静态最后弦乐TAG =ChapterFragment;
 @覆盖
 公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){
     查看列表视图= inflater.inflate(R.layout.activity_main,NULL);
     ListView控件mList =(ListView控件)listview.findViewById(R.id.chapterlist);
      //所需的列被绑定
      的String [] =列新的String [] {
        TDAdb.COL_CHAPTER,
        TDAdb.COL_CHAPTERTITLE};
      //该数据将被绑定到XML定义的视图
      INT []为= INT新[] {
        R.id.chapter1,
        R.id.chaptertitle1,      };      //创建从SimpleCursorAdapter适配器
      DataAdapter的=新SimpleCursorAdapter(
        getActivity(),
        R.layout.chapter_info,
        空值,
        列,
        至,
        0);
      mList.setAdapter(DataAdapter的);
      //确保装载机初始化和积极的。
      getLoaderManager()initLoader(0,null,则此)。
     返回列表视图; }
 @覆盖
 公共无效调用onStart(){
  super.onStart();
  Log.i(TAG,在onStart);
  displayListView();
  Log.i(TAG,在onStart结束);
 }
    @覆盖
    公共无效onAttach(活动活动){
        super.onAttach(活动);        //这将确保集装箱活动实施
        //回调接口。如果不是,它抛出一个异常
        尝试{
            mCallback =(ChapterSelectedListener)活性;
        }赶上(抛出ClassCastException E){
            抛出新ClassCastException异常(activity.toString()
                    +必须实现ChapterSelectedListener);
        }
    } @覆盖
公共无效onResume(){
  super.onResume();
  //开始一个新的或在这个管理器重新启动现有的装载机
  Log.i(TAGonResume);
  getLoaderManager()restartLoader(0,null,则此)。
 } 私人无效displayListView(){     Log.i(TAG启动displayListView);
  //所需的列被绑定
  的String [] =列新的String [] {
    TDAdb.COL_CHAPTER,
    TDAdb.COL_CHAPTERTITLE};
  //该数据将被绑定到XML定义的视图
  INT []为= INT新[] {
    R.id.chapter1,
    R.id.chaptertitle1,  };  //创建从SimpleCursorAdapter适配器
  DataAdapter的=新SimpleCursorAdapter(
    getActivity(),
    R.layout.chapter_info,
    空值,
    列,
    至,
    0);  //获取引用到ListView
  ListView控件的ListView =(ListView控件)getView()findViewById(R.id.chapterlist)。
  //指定适配器的ListView
  listView.setAdapter(DataAdapter的);
  //确保装载机初始化和积极的。
  getLoaderManager()initLoader(0,null,则此)。
  listView.setOnItemClickListener(新OnItemClickListener(){
   @覆盖
   公共无效onItemClick(适配器视图<>的ListView,观景,
     INT位置,长的id){
    //获取光标,定位在相应的行中的结果集
    光标光标=(光标)listView.getItemAtPosition(位置);    字符串chaptervalues​​elected =
    cursor.getString(cursor.getColumnIndexOrThrow(TDAdb.COL_CHAPTER));       mCallback.onChapterSelected(chaptervalues​​elected,位置);
        Toast.makeText(getActivity(),章+ chaptervalues​​elected,Toast.LENGTH_SHORT).show();    //开始一个新的意图更新/删除章节
    //传递的行ID创建内容的URI单行
    //意图chapterEdit =新意图(getBaseContext(),ChapterEdit.class);
    //捆绑包=新包();
    //bundle.putString(\"mode,更新);
    //bundle.putString(\"rowId,ROWID);
    //chapterEdit.putExtras(bundle);
    // startActivity(chapterEdit);   }
  }); } //这就是所谓当一个新的Loader需要创建。
 @覆盖
 公共装载机<&光标GT; onCreateLoader(INT ID,捆绑参数){
     Log.i(TAGonCreateLoader);
  的String [] =投影{
    TDAdb.KEY_ROWID,
    TDAdb.COL_CHAPTER,
    TDAdb.COL_CHAPTERTITLE};  CursorLoader cursorLoader =新CursorLoader(getActivity()
  TDAProvider.CONTENT_URI,投影,NULL,NULL,NULL);
  返回cursorLoader;
 } @覆盖
 公共无效onLoadFinished(装载机<&光标GT;装载机,游标数据){
     Log.i(TAGononLoadFinished);
  //交换新的光标(该框架将采取关闭照顾
        //老光标一旦我们回来。)
        dataAdapter.swapCursor(数据);
 } @覆盖
 公共无效onLoaderReset(装载机<&光标GT;装载机){
  //这就是所谓的当提供给onLoadFinished一个光标()
  //上述即将被关闭。我们需要确保我们没有
  //不再使用它。
     Log.i(TAGonLoaderReset);
  dataAdapter.swapCursor(NULL);
 }
}


解决方案

如果您已经使用了添加的方法 FragmentTransaction 您不能包含<片段标记布局。如果你刚刚离开你的主要活动XML是这样的:

 <?XML版本=1.0编码=UTF-8&GT?;
<的FrameLayout的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:ID =@ + ID / fragment_container
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent/>

I'm would like to make my Android application use Fragment Transactions, so that I can switch between various Fragments display their associated lists. My application worked fine prior to attempting to convert to just Fragment Transactions. In my initial activity_main.xml, I removed the android:name="com.birdsall.peter.chap.ChapterFragment", it is my understanding you can't use xml defined fragments with fragment transactions.

1) I can't seem to get the .add() within getSupportFragmentManager correct with it's parameters, even with code from a working example.
I have also attempted to use the newer version of FragmentTransactions to no avail.
I even took a working example of code using getSupportFragmentManager / FragmentTransactions, modified to use the names I had, it worked. I then imported that code into my application and it fails on the .add() syntax. I'm somewhat new to Android development and can't pinpoint where I'm going wrong.

Here is my main xml layout for the FrameLayout

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>

Here is the xml layout for the ChapterFragment ListView

chapterfragment.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>

Here is the layout for the details of the list 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>

Here is the MainActivity.java that I have modified. I left the 'setContentView(R.layout.activity_main);' as I thought I needed to create a view (even though it empty) to add the fragment view to.

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

}   ...

Here is my 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);
 } 


}

解决方案

If you are already using the add method of FragmentTransaction you must not include the <fragment tag in your layout. What if you just left your main activity XML like this:

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

这篇关于如何实现Android的碎片交易。新增语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆