lla*_*all 1 android extends class android-activity
我想要一个类"Utils",它将在我的代码中使用几种方法.例如,我有一个带有a textview和两个ImageButtons 的顶栏,必须在不同的活动上显示不同的文本和图标.
我发现自己在每个活动上写这样的东西:
(TextView) topBarText = (TextView) findViewById(R.id.topBarText);
topBarText.setText(R.id.mytextForThisView);
Run Code Online (Sandbox Code Playgroud)
我想在我的整个应用程序中找到一次ViewById,并调用一个方法setupTopBar(String text, R.id.iconForImageButton1, R.id.iconForImageButton2),甚至传递当前Activity的id,让方法找出文本和图像中显示的内容.
我创建了类Util,但它没有扩展Activity.问题是,如果没有,findViewById是不可访问的,所以我不能使用它.
在Android中做这样的事情是什么模式?
您的帮助方法应该是这样的
public static void setTopBarText(Activity act, int textId){
(TextView) topBarText = (TextView)act.findViewById(R.id.topBarText);
topBarText.setText(textId);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以从Activity进行静态导入并调用
setTopBarText(this, R.id.mytextForThisView);
Run Code Online (Sandbox Code Playgroud)