【问题标题】:multiple buttons in fragment, how to redirect to a different layout片段中的多个按钮,如何重定向到不同的布局
【发布时间】:2016-03-04 04:42:51
【问题描述】:

我有一个带有 8 个按钮的片段,我希望每个按钮都能引导我进入不同的布局,但我不知道该怎么做,我只有一个按钮可以工作,但我不知道如何放入其他七个按钮谁能帮帮我?

这是我目前所拥有的:

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


    View view = inflater.inflate(R.layout.pagina_principal, container, false);
    view.findViewById(R.id.btnazul).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(getActivity(), Rutas_azul.class));
        }
    });

    return view;


}

【问题讨论】:

  • 可以添加错误日志吗?
  • 您在这里的具体做法... 将 R.id.btnazul 更改为相应的按钮 id 并相应地执行操作 一个好的做法是声明按钮并让 Fragment 实现 OnClickListener。在 OnClick 方法中对视图 id 进行 switch-case 并执行相应的操作
  • 对 Intent 构造函数使用不同的第二个参数重复相同的操作
  • 如果你想切换另一个布局不同的活动,那么为什么不使用 Intent

标签: android android-fragments android-studio android-fragmentactivity


【解决方案1】:

您可以为所有按钮使用单击侦听器:

private final View.OnClickListener mListener = new View.OnClickListener() {
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button1:
                // do stuff
               break;
            case R.id.button2:
                // do stuff
               break;
            case R.id.button3:
                // do stuff
               break;
        }
    }
}

然后在你的 onCreateView 中

view.findViewById(R.id.button1).setOnClickListener(mListener);
view.findViewById(R.id.button2).setOnClickListener(mListener);
view.findViewById(R.id.button3).setOnClickListener(mListener);

为所有 8 个按钮执行此操作。

【讨论】:

  • 非常感谢!!你救了我的命! :D
【解决方案2】:

嗨@Alejandro Gurrola

让你的片段实现 View.OnClickListener

然后实现 onclcick 方法如下。

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button1:
            //Start activity one
            break;
        case R.id.button2
            //Start activiy two
            break;
        // Do this for all buttons.
    }
}

然后在片段的 onCreateView() 方法中执行以下操作。

Button button1 = view.findViewById(R.id.button1);
Button button2 = view.findViewById(R.id.button2);
// Do this for all the buttons

.

button1.setOnClickListener(this);
button2.setOnClickListener(this);
//Do this for all the butons.

希望这就是你要找的。​​p>

【讨论】:

  • 我已经这样做了,但 onCreateView 无法识别 view.findViewById 中的视图
  • 查看视图 = inflater.inflate(R.layout.pagina_principal, container, false);是你的看法
  • 我按照你说的做了,现在错误不同了:/由于长度原因,我无法粘贴代码
  • 至少发布错误以便我们了解根本原因@AlejandroGurrola
猜你喜欢
  • 2017-07-22
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2014-03-26
  • 1970-01-01
相关资源
最近更新 更多