【问题标题】:Two buttons, it mix between the links两个按钮,它在链接之间混合
【发布时间】:2014-06-29 14:55:57
【问题描述】:

两个按钮,它在链接之间混合

我有一个带有两个按钮的页面,当我有第一个按钮时,它把我带到了链接,当我有第二个按钮时,第一个按钮停止了,第二个按钮把我带到了第二个链接,求助! PageOne.jave

package com.d.di;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;

public class PageOne extends Activity {

    Button button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.abus);
        setContentView(R.layout.weoff);
    }
}

MainActivity.java

package com.d.di;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    Button button;

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

    public void addListenerOnButton() {
        final Context context = this;
        button = (Button) findViewById(R.id.abus);
        button = (Button) findViewById(R.id.weoff);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(context, PageOne.class);
                startActivity(intent);

            }

        });

        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(context, PageOne.class);
                startActivity(intent);

            }

        });

    }

}

【问题讨论】:

  • PageOne 将使用 R.layout.weoff 而不是 R.layout.abus 的布局。它取代了布局而不是合并它们。
  • 我应该用什么代替它?
  • 您应该传递一些其他信息标签作为附加信息来识别要加载的布局。或者另一种方法是为 pageTwo 创建一个单独的活动。
  • 您需要两个在 PageOne 类中有两个 Button 实例

标签: java android xml eclipse


【解决方案1】:

这里

button = (Button) findViewById(R.id.abus);
button = (Button) findViewById(R.id.weoff);

它替换了对R.id.weoff 的旧引用,因此您将添加侦听器到weoff,两次替换旧侦听器,然后将其设置为指向PageOne.class 的侦听器。

你应该使用两个变量

button1 = (Button) findViewById(R.id.abus);
button2 = (Button) findViewById(R.id.weoff);

button1.setOnClickListener(new OnClickListener() {

button2.setOnClickListener(new OnClickListener() {

由于两个监听器指向同一个Intent,你可以只创建一次监听器并放同一个吗?

【讨论】:

  • 您创建了两个变量?你加了两个redric?因为现在这两个按钮重定向到 PageOne。
  • 它可以工作,但它显示两个按钮只显示第二个链接!
  • 你应该只在一个布局中添加两个按钮。
  • 它给了我一个错误 -- button1 = (Button) findViewById(R.id.abus); button2 = (Button) findViewById(R.id.weoff); button1.setOnClickListener(new OnClickListener() { button2.setOnClickListener(new OnClickListener() {
  • 什么错误?当然你应该调整这些例子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多