简体   繁体   English

如何以编程方式添加 FloatingActionButton

[英]How to add a FloatingActionButton programatically

I'm trying to add a FloatingActionButton to my Android App whick has a WebView as the app content, but I can't figure out how.我正在尝试将FloatingActionButton添加到我的 Android 应用程序中,其中有一个 WebView 作为应用程序内容,但我不知道如何。

Where and how should I go about it?我应该去哪里以及如何去做?

Thank you all in advance.谢谢大家。

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    private WebView mWebview ;

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

        binding = ActivityMainBinding.inflate(getLayoutInflater());

        mWebview  = new WebView(this);

        mWebview.loadUrl("https://www.Camp-Ann.com/");

        setContentView(mWebview);

        FloatingActionButton reloadTab = getReloadFab(this);
    }

    public FloatingActionButton getReloadFab(Context context) {
        FloatingActionButton fab = new FloatingActionButton(context);

        fab.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                mWebview.loadUrl( "javascript:window.location.reload( true )" );
            }
        });
        return fab;
    }
}

What you are trying is possible.你正在尝试的是可能的。 But, according to the approach you are using, it is wrong.但是,根据您使用的方法,这是错误的。

  1. So, first of all, you are not using binding so, we will use that.所以,首先,你没有使用绑定,所以我们将使用它。
  2. You are not adding the fab to the view, so we will add that.您没有将晶圆厂添加到视图中,因此我们将添加它。

Now, to solve the problem, we will do both the things mentioned above with our final code looking like this:现在,为了解决这个问题,我们将完成上述两件事,最终代码如下所示:

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration appBarConfiguration;
    private ActivityMainBinding binding;

    private WebView mWebview ;

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

        binding = ActivityMainBinding.inflate(getLayoutInflater());

        setContentView(binding.getRoot());

        mWebview  = new WebView(this);
   
        binding.getRoot().addView(mWebView);

        mWebview.loadUrl("https://www.Camp-Ann.com/");

        FloatingActionButton reloadTab = getReloadFab(this);

        binding.getRoot().addView(reloadTab);
        
    }

    public FloatingActionButton getReloadFab(Context context) {
        FloatingActionButton fab = new FloatingActionButton(context);

        fab.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                mWebview.loadUrl( "javascript:window.location.reload( true )" );
            }
        });
        return fab;
    }
}

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

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