我是Android和Java的初學者,我剛剛看到一些在java中使用getter和setter方法的視頻,當我在同一個類中使用getter和setter方法時,該方法運行良好。但是,當我使用setter方法從主類設置圖像的位置,並嘗試從我的片段類使用getter方法檢索它返回0.有一個類似的問題在stackoverflow中問我不明白。請幫我..我 主類:Getter從其他類調用時返回0
public class Login_Register extends Activity implements OnClickListener {
Login login = new Login();
Register register = new Register();
ImageButton LoginB;
ImageButton RegisterB;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_register);
FragmentManager fmanager = getFragmentManager();
LoginB = (ImageButton) findViewById(R.id.login_button);
RegisterB = (ImageButton) findViewById(R.id.Reg_button);
LoginB.setOnClickListener(this);
RegisterB.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Positions pos = new Positions();
pos.setLIpos(LoginB.getY());
pos.setRIpos(RegisterB.getY());
FragmentTransaction transaction = fmanager.beginTransaction();
switch (v.getId()) {
case R.id.login_button:
transaction.add(R.id.Parent, login, "Loginf");
transaction.addToBackStack("Login");
break;
case R.id.Reg_button:
transaction.add(R.id.Parent, register, "registerf");
transaction.addToBackStack("registerf");
break;
default:
break;
}
transaction.commit();
// TODO Auto-generated method stub
}
}
我的片段類:
public class Login extends Fragment implements OnGlobalLayoutListener {
EditText UN, Pass;
View loginimage, loginusing, loginlayout;
// Login_Register Lg=new Login_Register();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View login = inflater.inflate(R.layout.login, container, false);
// TODO Auto-generated method stub
UN = (EditText) login.findViewById(R.id.UsernameL);
Pass = (EditText) login.findViewById(R.id.PassswordL);
loginimage = login.findViewById(R.id.LoginImage);
loginusing = login.findViewById(R.id.loginusing);
loginlayout = login.findViewById(R.id.LoginLayout);
loginimage.getViewTreeObserver().addOnGlobalLayoutListener(this);
UN.getBackground().setAlpha(50);
Pass.getBackground().setAlpha(50);
Positions poss=new Positions();
float f=poss.getLIpos();
ObjectAnimator.ofFloat(loginusing, View.ALPHA, 0,1).setDuration(1000).start();
return login;
}
}
類具有setter和getter方法:
public class Positions {
private float LIpos=0;
private float RIpos=0;
public Positions() {
// TODO Auto-generated constructor stub
}
public float getLIpos() {
Log.i("allalalla", ""+LIpos);
return LIpos;
}
public void setLIpos(float lIpos) {
LIpos = lIpos;
}
public float getRIpos() {
return RIpos;
}
public void setRIpos(float rIpos) {
RIpos = rIpos;
}
}
太簡單了......感謝您的幫助....... – Harsha 2014-09-03 08:03:16
從長遠看,建議人們使用靜態變量可能沒有幫助。 Java是一種面向對象的語言,靜態語言在語言上是一種非OO語言。避免它們是可能的。 – 2014-09-03 08:05:25
@StephenC用2個更合適的解決方案更新了我的答案,顯示了其中一個解決方案的示例。 – Simas 2014-09-03 08:06:53