片段

时间:2017-10-01 15:31:29

标签: android xml fragment

我正在开发一个应用程序,它运行得很好但是有一个问题,当我在我的片段代码中没有写id但在使用id属性后运行正常并且问题是我没有使用它时它会崩溃#39 ; s id在我的应用程序中的任何地方

这是xml文件

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal"
>
 <fragment
  class="com.hfad.workout.WorkoutList"
  android:layout_width="0dp"
  android:layout_height="match_parent"
  android:layout_weight="2"
  android:id="@+id/listfrag"
  />
 <FrameLayout
  android:layout_width="0dp"
  android:layout_height="match_parent"
  android:text="second text view"
  android:layout_marginTop="20dp"
  android:id="@+id/fragcont"
  android:layout_weight="3"
  />
  </LinearLayout>

workoutlist.jav

 public class WorkoutList extends ListFragment {

    MainActivity ma;
 static interface WorkoutListListener{
 void clickme(long at);
 }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ArrayAdapter<Workout> arrayAdapter = new ArrayAdapter<Workout>(
                inflater.getContext(), android.R.layout.simple_list_item_1, 
  Workout.workout);
        setListAdapter(arrayAdapter);

        return super.onCreateView(inflater, container, savedInstanceState);
    }
    @Override
    public void onAttach(Context ac){
        super.onAttach(ac);
        this.ma =(MainActivity) getActivity();

    }

    public void onListItemClick(ListView v, View vi, int position, long id){
        ma.clickme(id);

    }
}

2 个答案:

答案 0 :(得分:0)

这是因为如果你没有指定片段id,那么FragmentManager在重新创建后无法恢复它。 您必须指定片段ID或标记。

答案 1 :(得分:0)

在活动可以与其片段对话之前,活动首先需要 得到它的参考。要获得对片段的引用,请先进行 使用。获取对活动的片段管理器的引用 活动的getFragmentManager()方法。然后你用它 获取片段引用的findFragmentById()方法:

  

findFragmentById()是一个   有点像findViewById()   除了你用它来获得一个   引用片段

getFragmentManager().findFragmentById(R.id.fragment_id)