我的要求是与另一个模块(例如库模块)共享一个模块(例如应用程序)的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)
状态。但是当单击按钮时,什么也没有发生。我要去哪里错了?还是这种方法行得通?如果没有,有什么办法吗?
PS:我也尝试过通过意图传递按钮ID并通过该ID查找视图。完全相同的结果。
另外,在您拒绝投票之前,请在下面的评论中让我知道原因。这样我就可以知道我在想哪里错了。
试试这个,它的工作
代替
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();
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句