繁体   English   中英

如何将 Button 添加到我的 Wear OS 应用程序?

[英]How can I add a Button to my wear OS app?

我正在向我的第一个 Wear OS 应用程序添加一个 Button。 当我遵循现有 Android 应用程序的模型时,由于“WearableActivity”与“Activity”似乎存在差异。 我无法定义 OnClickListener。

在我的创建中是这样的:

bottomButton = findViewById(R.id.bottomButton);
        setListener();

后来在主要活动来源是这个

void setListener()
    {
            bottomButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) // toggle between report and graph display
            {   if (showGraph)
                    {showReport=true; showGraph=false;bottomButton.setText("show Report");}
                else
                    {showReport=false;showGraph=true;bottomButton.setText("show Graph");}



            }  // end, onClick
        }); // end, setOnClickListener
    } // end, setListener()

在这两种情况下,按钮都是在 XML 中定义的,并按如下方式找到和使用

OkButton = (Button) findViewById(R.id.OkButton);
OkButton.setOnClickListener(this);

无论如何它都可以编译。 我可以访问按钮中的项目,例如文本。 但是当我更改文本时,它不会出现在屏幕上。 当我按下模拟器中的按钮时,它不会注册任何操作。

问题不在于您的代码,而在于 Android Wear 模拟器。 您的磨损模拟器处于环境(低功耗)模式。 单击仿真器窗口顶部的 可在交互式(全功率)和环境模式(低功率)之间切换。

在此处输入图片说明

如何在wear os 应用程序中定义和使用按钮。

与在移动端完成的方式相同。 下面是一个例子

public class MainActivity extends WearableActivity implements View.OnClickListener {
    Button clickMeButton;
    TextView textView;
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        setAmbientEnabled();

        clickMeButton = findViewById(R.id.click_me_button);
        textView = findViewById(R.id.test_textview);
        clickMeButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        count++;
        textView.setText("I am clicked: "+count);
    }


    @Override
    public void onEnterAmbient(Bundle ambientDetails) {
        // Handle entering ambient mode
        super.onEnterAmbient(ambientDetails);
        Log.e("Hello", "I'm ambient");
    }

    @Override
    public void onExitAmbient() {
        // Handle exiting ambient mode
        super.onExitAmbient();
        Log.e("Hello", "exit ambient");
    }

    @Override
    public void onUpdateAmbient() {
        // Update the content
        super.onUpdateAmbient();
        Log.e("Hello", "update ambient: " + isAmbient());
    }

}

以下是上述活动的结果(注意:单击模拟器窗口顶部可在交互模式和环境模式之间切换):

在此处输入图片说明

编辑

为避免在活动实施View.OnClickListener打电话时您可以通过View.OnClickListener的实例setOnClickListenerOkButton像你已经做了bottomButton

OkButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {   
                //do something when OkButton is clicked
            } 
        });

暂无
暂无

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

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