gpt4 book ai didi

java - 如果从帮助程序类调用,则 Activity 方法中的 Android findViewById 不起作用

转载 作者:行者123 更新时间:2023-12-01 13:33:26 27 4
gpt4 key购买 nike

我在主要 Activity 中有这个方法:

 public void setPositionToView (Context ctx, List<Address> addresses) {
try {

String street = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);

Log.i(AppHelper.APP_LOG_NAMESPACE, street);

// display toast message with success state
Toast.makeText(ctx, "TEST", Toast.LENGTH_LONG).show();

// change state text to success and colorize text green
TextView eanTv = (TextView) findViewById(R.id.street);
eanTv.setText("Test");
//stateTv.setTextColor(getResources().getColor(R.color.green));

} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE, "getAndSavePosition method cannot be processed", e);
e.printStackTrace();
}
}

方法作为辅助类(从 Activity 扩展)的回调进行调用。

如果在方法中我尝试调用:

TextView eanTv = (TextView) findViewById(R.id.street);

我总是遇到空指针异常,但是如果我尝试像这样从 Main Activity 方法中的 onCreate 方法调用,一切都很好:

  public  void colorizeIt () {
try {

TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setText("This is O.K");
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE, "getAndSavePosition method cannot be processed", e);
e.printStackTrace();
}
}

我尝试为此找到一些解决方案,但没有运气,我应该创建一些布局、 View 实例或类似于下面示例的内容吗?

LayoutInflater in = getLayoutInflater() ;
View layout = in.inflate(R.layout.toast_layout, (ViewGroup) findViewById ( R.id.toast_layout_root ) ) ;

感谢您的任何建议和示例..

最佳答案

public void setPositionToView (Context ctx, List addresses,View mainview) { try {

String street = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);

Log.i(AppHelper.APP_LOG_NAMESPACE, street);

// display toast message with success state
Toast.makeText(ctx, "TEST", Toast.LENGTH_LONG).show();

// change state text to success and colorize text green
TextView eanTv = (TextView) mainview.findViewById(R.id.street);
eanTv.setText("Test");
//stateTv.setTextColor(getResources().getColor(R.color.green));

} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE, "getAndSavePosition method cannot be processed", e);
e.printStackTrace();
}

}

然后像这样调用

setPositionToView (ctx, addresses,(ViewGroup)view.getParent());

关于java - 如果从帮助程序类调用,则 Activity 方法中的 Android findViewById 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21427586/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com