【问题标题】:Multiple buttons in single page navigating each button to different page in android studio单个页面中的多个按钮将每个按钮导航到 android studio 中的不同页面
【发布时间】:2015-10-29 21:51:58
【问题描述】:

请在 android studio 中解决这个问题,我是应用程序开发的新手。 我想在一个页面中创建 3 个按钮并将每个按钮导航到每个不同的页面。 我需要java代码,即“Mainactivity.java” 我已经声明了 3 个按钮 ID 我已经在应用清单中设置了所有内容。 我一次只能导航一个按钮,但如何安排所有三个按钮进行导航?

公共类 MainActivity 扩展 AppCompatActivity 实现 View.OnClickListener {

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

    Button buttonWRGL = (Button)findViewById(R.id.buttonWRGL);
    Button buttonHNK = (Button)findViewById(R.id.buttonHNK);
    Button buttonKZP = (Button)findViewById(R.id.buttonKZP);

    buttonWRGL.setOnClickListener(this);
    buttonHNK.setOnClickListener(this);
    buttonKZP.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.buttonWRGL:

            break;
        case R.id.buttonHNK:
            break;
        case R.id.buttonKZP:
            break;
    }
}

}

【问题讨论】:

  • 您可以编辑您的问题以显示您已经编写的代码吗?

标签: java android android-layout


【解决方案1】:

您的问题似乎不清楚,但我想您是在问如何通过单击按钮来加载另一个布局/活动/片段。

嗯,这取决于您要执行三个操作中的哪一个:

1) 为了加载另一个布局,您需要在视图中为新布局充气;为此,您需要清除实际布局并为新布局充气。 下面是一些示例代码:

//you may change it to whichever layout you used
LinearLayout ll = (LinearLayout) findViewById(R.id.mainLayout);

//remove previous view
ll.removeAllViews();

//set the new view
setContentView(R.layout.new_layout);

2) 如果你想开始一个新的活动,你需要使用一个 Intent 并加载它。 示例代码:

//create the new intent; it will refer to the new activity
Intent intent = new Intent(this, NewActivity.class);

//pass any data to the new activity; cancel this line if you don't need it
intent.putExtra(extra_title, extra)

//start the new activity
startActivity(intent);

3) 如果要更改片段,则需要执行事务。 示例代码:

//create the new fragment
Fragment newFragment = new MyFragment();

//start a fragment transaction
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

//replace the old fragment with the new
transaction.replace(R.id.frame, newFragment).commit();

希望这会有所帮助;如果不是,请尝试编辑您的问题以澄清您的意思。


编辑:

您应该为每个按钮添加一个新的 OnClickListener,但我的做法与您现在的做法不同。 我会做这样的示例代码:

buttonWRGL.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent(this, NewActivity1.class);
        startActivity(intent);
    }
});

对于每个按钮。在这段代码中,我直接将特定的 OnClickListener 附加到按钮上;它将包含您需要的意图。 您可以将其复制到每个按钮中,甚至是 10k 按钮,您只需将意图声明中的活动名称更改为要启动的活动即可。

【讨论】:

  • 谢谢“Tenik”,你对我来说有点清楚。我想使用意图打开新活动,我可以从一个按钮打开新活动,但是如何对所有三个按钮使用意图,以便我可以打开第一个按钮到一个新活动,第二个按钮到另一个新活动和第三个按钮到另一项新活动。
  • 再次感谢您,我有一个清晰的想法,并会按照您指导的方式尝试。
  • 好的 :) 如果可行,请将答案加粗为“正确”:)
  • 非常感谢它工作正常,我已经为每个按钮设置了 OnClickListener。
猜你喜欢
  • 2021-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 2010-10-08
相关资源
最近更新 更多