【问题标题】:id attribute in fragments片段中的 id 属性
【发布时间】:2017-10-01 15:31:28
【问题描述】:

我正在开发一个应用程序,它运行得很好,但是当我不在我的片段代码中写入 id 但在使用 id 属性后运行良好时,它会崩溃,问题是我没有在任何地方使用它的 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);

    }
}

【问题讨论】:

    标签: android xml fragment


    【解决方案1】:

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

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

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

    【讨论】:

    • @neha 但在我的应用程序中我没有使用(R.id.listfrag)?
    • @ankit joshi 你能显示你的WorkoutList.java 代码
    • 你在MainActivity中使用implements WorkoutListFragment.WorkoutListListener
    • 这是什么原因?? @priya 耆那教
    • 如果你回顾一下fragment的生命周期,你会发现当fragment被附加到activity时,fragment的onAttach()方法被调用了activity的值。如果你不定义ID,activity怎么会知道它
    【解决方案2】:

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

    【讨论】:

    • 所以,它永远不会运行,或者它只是在我的情况下发生?
    • @ankitjoshi 应用程序崩溃时的日志消息是什么
    • 我不记得了,但这就像 xml 二进制文件中的错误...和充气机错误...我不确定,因为在那之后我使用了 id 属性
    • @ankitjoshi 如果你没有 id 那么片段管理器将无法恢复它,所以你应该添加它。
    • @ankitjoshi 可能你可以设置标签属性,它也可以工作;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2013-10-19
    • 2013-05-24
    • 2014-10-17
    相关资源
    最近更新 更多