【问题标题】:Adding a button that launches a new List Activity to a Fragment将启动新列表活动的按钮添加到片段
【发布时间】:2013-08-17 04:30:52
【问题描述】:

我有一个片段,我也在 XML 中添加了一个按钮。我想让这个按钮启动一个新的菜单,所以我把它做成了一个列表活动java类,让它在点击时指向它,我的问题是,我在哪里添加按钮和onclick方法?在页面片段类中?当我尝试这样做时,它当然无法解析我用来定义按钮的方法“findviewbyid”。它还会为 setContentView 引发相同的错误。我也尝试将此代码放在片段的 Activity 类中,但是当我这样做时应用程序无法加载。这是我试图添加以使按钮工作的代码:

    Button chOptions =  (Button) findViewById(R.id.bOptions);
    chOptions.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.channel_menu);
        }
    });

channel_menu 是我创建的列表活动。这是我的清单声明:

      <activity android:name=".ChannelMenu"
              android:label="Channel Options"
              android:theme="@android:style/Theme.Holo">
        <intent-filter>
            <action android:name="android.intent.action.CHANNELMENU" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

谢谢!

【问题讨论】:

    标签: android button android-activity android-fragments


    【解决方案1】:

    如下图在onActivityCreated()中添加代码并使用getView()方法

     @Override
    public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    // get the button view
    Button chOptions =  (Button) getView().findViewById(R.id.bOptions);
    // set a onclick listener for when the button gets clicked
    chOptions.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            setContentView(R.layout.channel_menu);
        // Start new list activity
        public void onClick(View v) {
            Intent mainIntent = new Intent(getActivity(),
                    CarouselActivity.class);
            startActivity(mainIntent);
        }
    });
    
    }
    

    【讨论】:

    • 感谢您的提示,我的 Fragment 类有一个 oncreate 视图,我决定只使用上下文菜单,似乎我无法将其添加到 oncreate 视图方法中。任何想法,该方法都会膨胀 xml 布局,仅此而已。我试图让它膨胀一个上下文菜单,但我似乎遗漏了一些东西。
    • 完全发现我在错误的活动中工作,对不起,我应该从这里开始。谢谢。
    【解决方案2】:

    如果您想将一些小部件注入到Fragment 的支持视图中,那么您应该在onCreateView 中对您创建的视图有一个全局引用:

    View root;
    
           @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
    
                root = inflater.inflate(R.layout.flash_cards_box, container, false);
    
                context = getActivity().getApplicationContext();
    
        }
    

    然后将小部件注入其他地方:

    root.findViewById(...);
    

    对于访问setContentView,可以通过Activity 类访问:

    getActivity().setContentView(....)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多