java Android Studio PageViewer findViewById(R.Id.FragmentItemeAm)返回null
我得到了一个包含3个片段的页面查看器(主页、注册、登录)。我想要登录片段的EditText中的文本。如果调用findViewById,则每次都返回null。那我错了什么? MyPageViewer。爪哇:
public class MyViewPager extends ViewPager {
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
initMyScroller();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Never allow swiping to switch between pages
return false;
}
private void initMyScroller() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
scroller.set(this, new MyScroller(getContext()));
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyScroller extends Scroller {
public MyScroller(Context context) {
//super(context, new LinearInterpolator()); // my LinearInterpolator
super(context, new DecelerateInterpolator());
}
@Override
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
super.startScroll(startX, startY, dx, dy, duration);
}
}
}
登录片段。爪哇:
import 安卓.os.Bundle;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.widget.Button;
import 安卓x.fragment.app.Fragment;
public class LoginFragment extends Fragment {
public LoginFragment() {
// Required empty public constructor
}
public static LoginFragment newInstance(){
LoginFragment frag = new LoginFragment();
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_login, container, false);
}
}
你的登录。xml:
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
安卓:orientation="vertical"
安卓:gravity="center"
安卓:focusable="true"
安卓:focusableInTouchMode="true">
<LinearLayout
安卓:layout_width="280dp"
安卓:layout_height="wrap_content"
安卓:orientation="vertical"
安卓:gravity="center"
安卓:layout_centerInParent="true">
<EditText
安卓:id="@+id/edt_login"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:hint="Username / Email"
安卓:imeOptions="actionNext"
安卓:inputType="textEmailAddress"
安卓:drawableLeft="@drawable/ic_user"
安卓:drawablePadding="15dp"/>
<EditText
安卓:id="@+id/edt_pw"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:hint="Passwort"
安卓:imeOptions="actionDone"
安卓:inputType="textPassword"
安卓:drawableLeft="@drawable/ic_lock"
安卓:drawablePadding="15dp"/>
<com.ornach.nobobutton.NoboButton
安卓:id="@+id/btn_login"
安卓:layout_width="130dp"
安卓:layout_height="wrap_content"
安卓:layout_marginTop="30dp"
安卓:padding="10dp"
安卓:onClick="GoToMenu"
app:nb_backgroundColor="@安卓:color/transparent"
app:nb_borderColor="#666"
app:nb_borderWidth="1dp"
app:nb_focusColor="#DDD"
app:nb_text="ANMELDEN"
app:nb_textSize="14sp" />
</LinearLayout>
</LinearLayout>
主要活动。爪哇:
public class MainActivity extends AppCompatActivity {
private final int TOTAL_PAGE=3;
private int sHeight;
private int sWidth;
View navBackground, navBottom;
View navHome, navLogin, navRegister;
EditText edt_pw, edt_login;
ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
public static byte[] getSHA(String input) throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public static String toHexString(byte[] hash)
{
BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 32)
{
hexString.insert(0, '0');
}
return hexString.toString();
}
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
SharedPreferences pref = this.getSharedPreferences("SystemSettings", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
if ((pref.getInt("avi", 0)) == 0) {
editor.putInt("avi", 1);
editor.commit();
Intent intent = new Intent(this, instruction.class);
startActivity(intent);
}
screenMeasurement();
navBackground = findViewById(R.id.img_nav_bg);
navBottom = findViewById(R.id.navbottom);
navHome = findViewById(R.id.nav_home);
navLogin = findViewById(R.id.nav_login);
navRegister = findViewById(R.id.nav_register);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(1);
mSectionsPagerAdapter.getItem(2);
navBackground.post(new Runnable() {
@Override
public void run() {
int w = (int) (sWidth*2.5);
int h = w/2;
FrameLayout.LayoutParams bgParams = (FrameLayout.LayoutParams) navBackground.getLayoutParams();
bgParams.width = w;
bgParams.height = h;
//bgParams.leftMargin = -1*((w/2)-(sWidth/2));
bgParams.bottomMargin = (int) (-1*(h/2.5));
navBackground.requestLayout();
int left = (sWidth/2) - (w/2);
navBackground.setX(left);
resizeNavIcon(navHome,w);
resizeNavIcon(navLogin,w);
resizeNavIcon(navRegister,w);
}
});
}
private void resizeNavIcon(View view, int bgWidth){
int iconWidth = (bgWidth*43)/500;
int m = iconWidth/15;
LinearLayout.LayoutParams btnParams = (LinearLayout.LayoutParams) view.getLayoutParams();
btnParams.width = iconWidth;
btnParams.height = iconWidth;
btnParams.leftMargin = (int) (m*1.5);
btnParams.rightMargin = (int) (m*1.5);
btnParams.topMargin = m;
btnParams.bottomMargin = m;
view.setLayoutParams(btnParams);
view.requestLayout();
int p = (int) (iconWidth/3.5);
//Log.e("TAG","width: "+iconWidth+" Padding: "+ p);
view.setPadding(p,p,p,p);
}
private void screenMeasurement(){
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
sHeight = displayMetrics.heightPixels;
sWidth = displayMetrics.widthPixels;
}
public void onNavClick(View view){
moveBackground(view);
int d = Integer.parseInt(view.getTag().toString());
mViewPager.setCurrentItem(d);
}
private void moveBackground(View view){
int c = view.getLeft()+(view.getWidth()/2);
int left = c-(navBackground.getWidth()/2);
//navBackground.setX(left);
navBackground.animate().translationX(left);
}
public void GoToMenu(View view) {
edt_login = findViewById(R.id.edt_login);
edt_pw = findViewById(R.id.edt_pw);
Log.d("Test","PW: "+edt_pw.getText().toString());
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return RegisterFragment.newInstance();
case 2:
return LoginFragment.newInstance();
default:
return HomeFragment.newInstance();
}
}
@Override
public int getCount() {
return TOTAL_PAGE;
}
}
}
启动时的活动。xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<ImageView
安卓:id="@+id/img_nav_bg"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:src="@drawable/nav_background"
安卓:layout_gravity="bottom"/>
<LinearLayout
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
安卓:orientation="vertical">
<e.marco.gymdiary.MyViewPager
安卓:id="@+id/viewPager"
安卓:layout_width="match_parent"
安卓:layout_height="0dp"
安卓:layout_weight="1"/>
<LinearLayout
安卓:id="@+id/navbottom"
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:gravity="center"
安卓:orientation="horizontal"
安卓:layout_gravity="bottom"
>
<com.ornach.magicicon.IconButton
安卓:id="@+id/nav_login"
安卓:layout_width="60dp"
安卓:layout_height="60dp"
安卓:onClick="onNavClick"
安卓:padding="0dp"
app:mi_fontText=""
app:mi_iconColor="#FFF"
app:mi_typeface="font_awesome"
安卓:tag="0"
app:mi_shape="oval"/>
<com.ornach.magicicon.IconButton
安卓:id="@+id/nav_home"
安卓:layout_width="60dp"
安卓:layout_height="60dp"
安卓:onClick="onNavClick"
安卓:padding="0dp"
app:mi_fontText=""
app:mi_iconColor="#FFF"
app:mi_typeface="font_awesome"
安卓:tag="1"
app:mi_shape="oval"/>
<com.ornach.magicicon.IconButton
安卓:id="@+id/nav_register"
安卓:layout_width="60dp"
安卓:layout_height="60dp"
安卓:onClick="onNavClick"
安卓:padding="0dp"
app:mi_fontText=""
app:mi_iconColor="#FFF"
app:mi_typeface="font_awesome"
安卓:tag="2"
app:mi_shape="oval"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
行edt_pw.getText().toString()
不返回任何内容。请解释清楚。多谢各位
溴 马可
# 1 楼答案
根据您的代码,{}在片段中定义。xml并且您正在访问MainActivity中的
edt_pw
。java肯定会返回null,您需要在登录片段中初始化它我可以执行以下任一操作:
edt_pw
(好方法)edt_pw
的值传递给MainActivity# 2 楼答案
“您应该将每个片段设计为模块化和可重用的活动组件。”摘自https://developer.android.com/guide/components/fragments
目前,您的登录片段不是模块化的,它取决于MainActivity。java提供
onClick
方法GoToMenu
当单击
GoToMenu
按钮时,LoginFragment将存在(因为按钮位于片段内部),但在主要活动中。java是错误的
更好的方法是处理片段内部的按钮点击,以保持模块性
为此,请从
fragment_login.xml
文件中删除android:onClick="GoToMenu"
在
LoginFragment.java
中,为按钮设置一个OnClickListener
onCreateView
中的LoginFragment.java
看起来像:-然后,根据您想要对这些值执行的操作,您可能需要创建一个接口,以便在片段外传递这些值