android findViewById方法返回值为null
此 View 是自定义类
View .xml
<include
android:id="@+id/view_before_login"
layout="@layout/view_mypage_before_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
查看 Activity java( fragment )
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.view, container, false);
mBefore = (MemberBeforeLoginView)rootView.findViewById(R.id.view_before_login);
mAfter = (MemberAfterLoginView)rootView.findViewById(R.id.view_after_login);
mBefore.SetStateListener(this);
mAfter.SetStateListener(this);
route();
return rootView;
}
里面的xml是view_mypage_before_login.xml
<?xml version="1.0" encoding="utf-8"?>
<com.main.view.MemberAfterLoginView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/profile"
android:layout_width="137dp"
android:layout_height="121dp"
app:srcCompat="@drawable/empty" />
<Button
android:id="@+id/logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="logout" />
</com.main.view.MemberAfterLoginView>
com.main.view.MemberAfterLoginView.java
public class MemberAfterLoginView extends LinearLayout implements View.OnClickListener, MemberViewListener.MemberChildViewInterface {
private MemberViewListener mMemberListener = null;
private Button mBtnLogout = null;
public MemberAfterLoginView(Context context) {
super(context);
initialize(context);
}
public MemberAfterLoginView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initialize(context);
}
public MemberAfterLoginView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize(context);
}
private void initialize(Context context) {
/*LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.view_mypage_after_login, null);
*/
mBtnLogout = (Button) findViewById(R.id.logout);
}
...
为什么变量 mBtnLogout 为空? (初始化函数内部变量)
我的英语还不成熟。 抱歉。
最佳答案
private View initialize(Context context) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.view_mypage_after_login, null);
mBtnLogout = (Button) v.findViewById(R.id.logout);
return v;
}
该按钮是新的膨胀 View 的一部分。因为 inflate 结果尚未应用于 Activity,但 activity.findViewById
找不到它。
关于java - android findViewById 在 LinearLayout 中为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45687479/