簡體   English   中英

Android:嘗試在片段之間傳遞數據的問題

[英]Android: Issue trying to pass data between fragments

我試圖將一些數據從ListFragment傳遞到另一個Fragment。 列表顯示正常,但是當我單擊列表中的項目時,沒有任何反應,並且日志中也沒有任何顯示錯誤的內容。 我是android / java開發的新手,正在嘗試圍繞不同的概念(活動,片段,捆綁包等)進行總結。 來自iOS /目標C世界,我看到了在“視圖”之間傳遞數據所涉及的概念的相似之處,但我想我還沒有完全理解android的概念。

無論如何,下面是片段和布局。 有人可以幫我看看我要去哪里錯嗎? 非常感激。

主(fragment_ehschedule.xml)和列表視圖(schedule_info.xml)的布局:

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

 <EditText android:id="@+id/myFilter" 
  android:layout_width="match_parent"
  android:layout_height="wrap_content" 
  android:ems="10" 
  android:hint="@string/some_hint">
  <requestFocus />
 </EditText>

 <ListView android:id="@android:id/list" 
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" />

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

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textViewSessionTime"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:paddingTop="10dip"
            android:paddingBottom="10dip"
            android:text="sessiontime" />

        <TextView
            android:id="@+id/textViewScheduleDate"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="scheduledate"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/textViewSessionName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"
            android:text="sessionname"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

</FrameLayout>

片段詳細信息(fragment_ehschedule_detail.xml)的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:padding="10dp">

  <TextView android:id="@+id/sessionname_label"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="25dip"
            android:textStyle="bold"
            android:paddingTop="10dip"
            android:paddingBottom="10dip"
            android:textColor="#43bd00"/>

  <TextView android:id="@+id/scheduledate_label"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#acacac"/>

  <TextView android:id="@+id/sessiontime_label"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textStyle="bold"/>

</LinearLayout>

主視圖的類文件(EhallSchedFragment2.java)如下:

 public class EhallSchedFragment2 extends ListFragment{

     public static String strDate = null;

     private SQLiteDB sqlite_obj;
     private SimpleCursorAdapter dataAdapter;

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                 Bundle savedInstanceState) {
             super.onCreateView(inflater, container, savedInstanceState);
             final View v = inflater.inflate(R.layout.fragment_ehschedule, container, false);

    sqlite_obj = new SQLiteDB(getActivity());

    sqlite_obj.open();

    Cursor cursor = sqlite_obj.fetchAllSchedules();

     // The desired columns to be bound
     String[] columns = new String[] {
       SQLiteDB.KEY_SCHEDULEDATE,
       SQLiteDB.KEY_SESSIONNAME,
       SQLiteDB.KEY_SESSIONTIME,
       SQLiteDB.KEY_DESC
     };

     // the XML defined views which the data will be bound to
     int[] to = new int[] { 
       R.id.textViewScheduleDate,
       R.id.textViewSessionName,
       R.id.textViewSessionTime,
       R.id.textViewDesc,
     };

     // create the adapter using the cursor pointing to the desired data 
     //as well as the layout information
     dataAdapter = new SimpleCursorAdapter(
             getActivity(), R.layout.schedule_info, 
               cursor, 
               columns, 
               to,
               0);

     ListView listView = (ListView)v. findViewById(android.R.id.list);
     // Assign adapter to ListView
     listView.setAdapter(dataAdapter);

     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 exHallScheduleDate = 
                cursor.getString(cursor.getColumnIndexOrThrow("scheduleDate"));
       String exHallSessionName = 
                        cursor.getString(cursor.getColumnIndexOrThrow("sessionName"));
       String exHallSessionTime = 
                        cursor.getString(cursor.getColumnIndexOrThrow("sessionTime"));

       EhallSchedDetailFragment2 myDetailFragment = new EhallSchedDetailFragment2();

       Bundle bundle = new Bundle();

       bundle.putString("scheduleDate", exHallScheduleDate);
       bundle.putString("sessionName", exHallSessionName);
       bundle.putString("sessionTime", exHallSessionTime);

           myDetailFragment.setArguments(bundle);

           FragmentManager fragmentManager = getFragmentManager();

            myDetailFragment.setArguments(bundle);
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.frameLayout, myDetailFragment);
            transaction.remove(EhallSchedFragment2.this);

           /*
                * Add this transaction to the back stack. 
                * This means that the transaction will be remembered after it is 
                * committed, and will reverse its operation when later popped off 
                * the stack.
           */
               transaction.addToBackStack(null);

               transaction.commit();

       }
      });


     EditText myFilter = (EditText)v. findViewById(R.id.myFilter);
      myFilter.addTextChangedListener(new TextWatcher() {

       public void afterTextChanged(Editable s) {
       }

       public void beforeTextChanged(CharSequence s, int start, 
         int count, int after) {
       }

       public void onTextChanged(CharSequence s, int start, 
         int before, int count) {
        dataAdapter.getFilter().filter(s.toString());
       }
      });

      dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
             public Cursor runQuery(CharSequence constraint) {
                 return sqlite_obj.fetchScheduleByDate(constraint.toString());
             }
         });

    return v;
}

}

詳細信息視圖的類文件(EhallSchedDetailFragment2.java)如下:

 public class EhallSchedDetailFragment2 extends Fragment {

TextView scheduleDateDetail;
TextView sessionNameDetail;
TextView sessionTimeDetail;

@Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
   View view = inflater.inflate(R.layout.fragment_ehschedule_detail, null);

   scheduleDateDetail = (TextView)view.findViewById(R.id.scheduledate_label);
   sessionNameDetail = (TextView)view.findViewById(R.id.sessionname_label);
   sessionTimeDetail = (TextView)view.findViewById(R.id.sessiontime_label);

       Bundle bundle = getArguments();
          if(bundle != null){
           String schedDateDet = bundle.getString("scheduleDate");
           scheduleDateDetail.setText(schedDateDet);

           String sessNameDet = bundle.getString("sessionName");
           sessionNameDetail.setText(sessNameDet);

           String sessTimeDet = bundle.getString("sessionTime");
           sessionTimeDetail.setText(sessTimeDet);
          }
          return view;
}

}

您基本上需要四件事來獲得所需的東西:

  1. 您需要片段-稱為FragmentA
  2. 然后,您可以在該片段內或其自己的類文件中定義一個接口。 該接口將具有您必須調用的方法來通知活動。
  3. 然后在您的活動中,實現接口並覆蓋上面第2步中的方法。
  4. 要通知FragmentB,您真正需要做的就是在步驟3中覆蓋的方法內部調用其方法。

如前所述,您不應直接在片段之間進行通信。 這是一個很好的循序漸進教程,介紹如何執行上述所有步驟:

在片段與活動之間進行溝通

我希望這可以幫助您解決或逐步解決您的問題。

如果您使用的是ListFragment,則可以執行以下操作:

 @Override
 public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mListView = getListView();
    SetClicklListener(mListView);  
  }
 public void SetClicklListener(ListView listView){
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
            //Here you can catch the clicked item
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM