【问题标题】:Customize a xml layout in a fragment - Android在片段中自定义 xml 布局 - Android
【发布时间】:2023-03-14 06:10:01
【问题描述】:

我是 Android 编程新手。 我使用 ActionBarSherlock 和 NavigationTabs 创建了我的应用风格谷歌商店的主要 Activity,其中带有片段,每个片段都引用另一个 Activity(片段 1 片段 2 等),并且每个片段都膨胀一个布局。

但是,我习惯于在 xml 中创建布局,然后在 java 中自定义它们。根据一天中的时间,或根据数据库中的某些数据,为按钮提供功能等放置不同的文本。但是在片段类中,我什至不能使用 setContentView 来处理每个文本或按钮,并且设置使用我的数据库的上下文给我带来了问题。

如何在片段中自定义 xml 布局? 或者什么是正确的做法?

这是我的片段:

public class Fragment1 extends SherlockFragment{


public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    return inflater.inflate(R.layout.menu, container, false);

}

【问题讨论】:

    标签: android android-layout android-fragments layout-inflater


    【解决方案1】:

    这比你想象的要简单。 onCreateView instanciate au 返回 Fragment 的视图。正如您所说,在一个简单的 Activity 中,您使用 setContentView() 设置(并实例化)视图,然后使用 findViewById() 获取视图。

    findViewById() 要求视图返回您想要的视图项,您可以在返回之前从视图中调用它。像这样:

    public class Fragment1 extends SherlockFragment{
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View v = inflater.inflate(R.layout.menu, container, false);
    
        // For example, getting a TextView
        TextView tv = (TextView) v.findViewById(R.id.myTextView);
        // do your job
    
        return v;
    }
    

    【讨论】:

      【解决方案2】:

      到目前为止一切都很好,您只需要使用正在膨胀的视图来获取所有内容。

      这是一个例子

      View v = inflater.inflate(R.layout.menu, container, false);
      
      Button b = (Button)v.findViewById(r.id.button1);
      
      return v;
      

      【讨论】:

        【解决方案3】:

        onActivityCreated 内你可以使用:

        View mView = getView();
        TextView textView = (TextView) view.findViewById(R.id.theIdOfTextView);
        

        其中theIdOfTextViewR.layout.menu 中声明。

        getView() 返回你在onCreateView 中膨胀的View。只有在onCreateView 执行后才能使用它

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-21
          • 1970-01-01
          • 2013-01-10
          • 2012-03-16
          • 2015-03-20
          • 1970-01-01
          • 1970-01-01
          • 2013-01-13
          相关资源
          最近更新 更多