【问题标题】:button default selection issue when activity load活动加载时按钮默认选择问题
【发布时间】:2016-01-07 05:39:23
【问题描述】:

**

我的应用中有两个活动。当点击主页按钮时, 第二个活动正常开始。在第二个活动中有三个 按钮:-按钮 1,按钮 2,按钮 3。所以我想要一秒钟 活动开始,按钮 1 自动激活并显示 工作。

**

【问题讨论】:

  • 激活按钮 1 是什么意思。使其可见并隐藏其他 2 个按钮?
  • 使用 performClick();在按钮对象上将触发按钮的点击事件
  • 如果你想自动点击一个按钮然后使用代码button1.performClick();
  • 当活动加载时,我只想选择一个按钮,并希望将其背景更改为粉红色。其余两个按钮必须以白色背景取消选择
  • 让我们知道您尝试了多少 - 发布代码。

标签: android button android-activity


【解决方案1】:

第一步:制作一个按钮选择器xml,将其命名为“button_selector.xml”,以便在打开第二个活动时显示为活动状态

 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"><shape  android:shape="rectangle">
            <corners android:bottomLeftRadius="7dp" android:bottomRightRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp" />

            <solid android:color="@color/button_active_color" />
        </shape></item>

    <item android:state_focused="true"><shape android:shape="rectangle">
            <corners android:bottomLeftRadius="7dp" android:bottomRightRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp" />

            <solid android:color="@color/button_active_color" />
        </shape></item>

    <item><shape android:shape="rectangle">
            <corners android:bottomLeftRadius="7dp" android:bottomRightRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp" />

            <solid android:color="@color/button_inactive_color" />
        </shape></item>
</selector>

第二步:在第二个活动按钮 1 中单击我们上面定义的侦听器设置按钮选择器

 button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                button1.setBackgroundResource(R.drawable.button_selector);
            }
        });

第三步:(用于激活按钮)在第二个活动onCreate() 方法中,在findViewById() 初始化按钮1 后调用它为

  button1.performClick();

【讨论】:

  • 我试试 button1.performClick();但仍然无法正常工作。
【解决方案2】:

创建一个可绘制对象,将其应用于您的按钮 android:background 制作按钮 1 android:enabled="false"

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/pink" android:state_enabled="false"/>
    <item android:drawable="@color/white" android:state_enabled="true"/>
    <item android:drawable="@color/white"/>
</selector>


在您的所有按钮的活动setOnClickListener() 中。每当第二个活动开始运行按钮 1 任务。

    int lastSelectedViewId;

    @Override
    public void onClick(View view) {
        view.setEnabled(false);
        if (lastSelectedViewId != 0)
            findViewById(lastSelectedViewId).setEnabled(true);
        lastSelectedViewId = view.getId();

    }

【讨论】:

  • 对不起,但我希望当第二个活动加载时。那时按钮 1 自动激活。并单击按下并显示在单击事件中的内容。
  • 你运行过代码吗?它完全符合您的要求。第一次您必须运行默认任务或使用@Clairvoyant 所说的 performClick()。 (在这种情况下,您需要启用按钮 1。)
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-27
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多