Android从onOptionsItemSelected中

时间:2016-02-26 09:47:57

标签: java android android-fragments

为noob问题道歉。我有一个操作栏按钮,将一个片段注入主活动。当代码在onOptionsItemSelected块中时,代码工作正常,如下所示:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
        case R.id.action_chat:
            Log.v("Click", "Chat button");

            RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
            LinearLayout ll = new LinearLayout(this);
            ll.setId(999);
            getFragmentManager().beginTransaction().add(ll.getId(), ChatFragment.newInstance()).commit();
            mainLayout.addView(ll);
            break;
        case R.id.action_settings:
            intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            break;
    }


    return super.onOptionsItemSelected(item);
}

但我正在尝试让外部类处理片段插入(因为这也是其他活动需要的东西)。所以我称之为:

         case R.id.action_chat:
            ChatHandler chatHandler = new ChatHandler();
            chatHandler.goChat(View view);
            break;

在ChatHandler类上:

public class ChatHandler {
        public void goChat(View view) {
            Log.v("GoChat", "Start");
            RelativeLayout mainLayout = (RelativeLayout) view.findViewById(R.id.main_layout);
            LinearLayout ll = new LinearLayout(this);
            ll.setId(999);
            getFragmentManager().beginTransaction().add(ll.getId(), ChatFragment.newInstance()).commit();
            mainLayout.addView(ll);
        }
    }

我的问题是我需要在主要活动goChat(View?view?)中传递什么参数?如何从ChatHandler类引用主要活动,如下所示:LinearLayout ll = new LinearLayout(this) ;

谢谢!

2 个答案:

答案 0 :(得分:1)

将您的代码更改为此

public void goChat(Context context)
{
    Log.v("GoChat", "Start");
    RelativeLayout mainLayout = (RelativeLayout)  ((Activity)context).findViewById(R.id.main_layout);
    LinearLayout ll = new LinearLayout(context);
    ll.setId(999);
    getFragmentManager().beginTransaction().add(ll.getId(), ChatFragment.newInstance()).commit();
    mainLayout.addView(ll);
}

答案 1 :(得分:-1)

您应该将活动作为goChat方法

的参数传递
case R.id.action_chat:
        ChatHandler chatHandler = new ChatHandler();
        chatHandler.goChat(this);
        break;

然后在那堂课:

public void goChat(Activity activity) {
        Log.v("GoChat", "Start");
        RelativeLayout mainLayout = (RelativeLayout) activity.findViewById(R.id.main_layout);
        LinearLayout ll = new LinearLayout(activity);
        ll.setId(999);
        activity.getFragmentManager().beginTransaction().add(ll.getId(), ChatFragment.newInstance()).commit();
        mainLayout.addView(ll);
    }