繁体   English   中英

单页中的多个按钮将每个按钮导航到android studio中的不同页面

[英]Multiple buttons in single page navigating each button to different page in android studio

请在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;
    }
}

}

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

好吧,这取决于您要执行以下三个操作中的哪一个:

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个按钮)中复制此代码,您只需要使用要启动的活动来更改意图声明中的活动名称。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM