【问题标题】:How to access view of one module in another module in Android?如何在Android的另一个模块中访问一个模块的视图?
【发布时间】:2017-01-18 12:38:33
【问题描述】:

我的要求是与另一个模块(比如库模块)共享一个模块(比如应用程序)的 xml 视图。我该怎么做?

我已经尝试过这种方式,但是onClickListener的按钮不起作用。我哪里错了?

Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra(Config.LAYOUT_ID, R.layout.login_view);
startActivityForResult(intent, Config.LOGIN_REQUEST);

在 login_view.xml 中

<Button
android:id="@+id/login_button"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="4dp"
android:layout_weight="1"
android:tag="login_button"/>

在不同模块的 LoginActivity 的 onCreate 方法中

        int layoutId = getIntent().getIntExtra(Config.LAYOUT_ID, 0);
        if (layoutId != 0) {
            setContentView(layoutId);
            View rootView = LayoutInflater.from(getApplicationContext()).inflate(layoutId, null);

         loginButton = (Button)rootView.findViewWithTag("login_button");
         if (loginButton != null) {
            loginButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(LoginActivity.this, "Logging in...", Toast.LENGTH_SHORT).show();
                }
            });
        }

一切顺利,甚至控件进入if (loginButton != null) 状态。但是当按钮被点击时,什么也没有发生。我哪里错了?或者这种方法会奏效吗?如果没有,有什么办法吗?

P.S:我还尝试通过意图传递按钮 ID 并通过该 ID 查找视图。完全相同的结果。

【问题讨论】:

  • 试试公共静态内容变量?
  • 您的意思是在第二个活动中访问第一个活动的静态变量?但我的问题是模块应用程序依赖于模块库而不是相反的方式。
  • 不要听@phpdroid。这个建议很糟糕,除非你真的想造成内存泄漏。
  • 即使我不关心任何内存泄漏,这在我的情况下是不可能的,当然我会。无论如何,是否有任何可能的解决方案?

标签: android android-layout android-library


【解决方案1】:

试试这个吧

替换

 setContentView(layoutId);

  View rootView = LayoutInflater.from(getApplicationContext()).inflate(layoutId, null);
  setContentView(rootView );

更新这个。

int layoutId = getIntent().getIntExtra(Config.LAYOUT_ID, 0);
        if (layoutId != 0) {

            View rootView = LayoutInflater.from(getApplicationContext()).inflate(layoutId, null);
          setContentView(rootView );
         loginButton = (Button)rootView.findViewWithTag("login_button");
         if (loginButton != null) {
            loginButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(LoginActivity.this, "Logging in...", Toast.LENGTH_SHORT).show();
                }
            });
        }

【讨论】:

    猜你喜欢
    • 2022-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多