【问题标题】:How do I call an Activity within a TabHost?如何在 TabHost 中调用 Activity?
【发布时间】:2017-01-25 07:44:47
【问题描述】:

我有一个片段,在那个片段中我有一个可以调用另一个活动的按钮

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

  // Inflate the layout for this fragment
  View view = inflater.inflate(R.layout.fragment_test_fragment, container, false);

  Button button = (Button) view.findViewById(R.id.button2);
  button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          Intent i = new Intent(getActivity(), AnotherPage.class);
          startActivity(i);
        }
    });

现在可以正常工作了。

但是,现在我想在我在这个片段中创建的 TabHost 中做同样的事情。

那么如何在我的标签中调用getActivity()

我试过了:

public class tab_two_graph extends AppCompatActivity {

  View v;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tab_two_graph);

     Intent intent = getParent().getIntent();
     v = intent.getParcelableExtra("view");

    Button b = (Button) findViewById(R.id.button2);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           Intent i = new Intent(v.getActivity(), Alert_main_page.class);
            startActivity(i);
        }
    });

  }

但它只会抛出错误。

【问题讨论】:

  • 查看 v; ---尝试做“公开决赛”。并给出错误内容(Runtime 或Сompiler 不接受语法?)
  • 错误是什么?

标签: android android-fragments android-tabhost fragment-tab-host


【解决方案1】:

只是为了在此处为答案添加更多信息。

您不必传递一个 Activity 来启动另一个 Activity。您需要传递一个上下文,可以使用tab_two_graph.this 访问它。这就是为什么以下工作:

startActivity(new Intent(tab_two_graph.this, Alert_main_page.class));

【讨论】:

    【解决方案2】:

    您需要使用当前活动而不是您的视图来调用它。因此,您可以使用以下方式调用它:

    Button b = (Button) findViewById(R.id.button2);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent i = new Intent(tab_two_graph.this, Alert_main_page.class);
                startActivity(i);
            }
        });
    

    请阅读Starting Another Activity

    【讨论】:

      【解决方案3】:

      公共类 tab_two_graph 扩展“AppCompatActivity”

      试试这个

      Intent i = new Intent(tab_two_graph.this, Alert_main_page.class);
                  startActivity(i);
      

      【讨论】:

        【解决方案4】:

        试试这个

        Intent i = new Intent(((<YourActivityName>) getActivity()), AnotherPage.class);
                    startActivity(i);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-30
          • 1970-01-01
          相关资源
          最近更新 更多