使用数据库值设置 TextView

为具有给定字符串和数据库中的某些值的文本视图设置文本的最佳做法是什么?


我的主要活动:


MyModel model;


TextView title = (TextView) findViewById(R.id.tvTitle);

title.setText("Username: ", model.getName());

我的模特


private String name;


public String getName() {

    return name;

}

到目前为止我找不到解决方案。


ITMISS
浏览 148回答 3
3回答

茅侃侃

方法setText()有几个签名,但您需要的是:public final void setText(CharSequence 文本)所以你可以这样做:title.setText("Username:&nbsp;"&nbsp;+&nbsp;model.getName());但是AS通常在这些情况下抱怨你应该避免在里面连接字符串setText(),所以你可以做的是:String&nbsp;str&nbsp;=&nbsp;"Username:&nbsp;"&nbsp;+&nbsp;model.getName(); title.setText(str);您还应该考虑将文字值存储"Username: "在以下资源中:<string&nbsp;name="username">Username:</string>并像这样使用它:String&nbsp;str&nbsp;=&nbsp;getResources().getString(R.string.username)&nbsp;+&nbsp;model.getName(); title.setText(str);

叮当猫咪

创建 getter 和 setter 是一种很好的做法,您可以在为模型定义变量后在 Android Studio 中自动生成它们。除此之外,我不知道为什么在你getName()的方法中想要返回一个 long 而你实际上是在返回一个字符串。更改long为String像这样 :&nbsp; public String getName() {&nbsp; &nbsp; &nbsp; &nbsp; return mName;&nbsp; &nbsp; }&nbsp; &nbsp; public void setName(String name) {&nbsp; &nbsp; &nbsp; &nbsp; mName = name;&nbsp; &nbsp; }

白衣非少年

其他人所说的关于在 setText 方法之外连接字符串的所有内容都是有效的。至于在 Activity 或 Fragment 中的位置(我在此示例中使用 Fragment),我使用以下约定:在我的方法之外的类主体中声明我的类字段(用于类范围的访问)public class MyFragment extends Fragment {&nbsp; &nbsp; private TextView titleView;&nbsp; &nbsp; public MyFragment() {&nbsp; &nbsp; //Constructor&nbsp; &nbsp; }&nbsp; &nbsp; // and so on ...}然后,在 Fragment 膨胀后找到我的 TextView 引用,如果需要立即设置它的值// ...@overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)&nbsp; &nbsp; View view = inflater.inflate(R.layout.fragment_container, container, false);&nbsp; &nbsp; titleView = view.findViewById(R.id.title);&nbsp; &nbsp; String titleStr = "Username: " + model.getName();&nbsp; &nbsp; titleView.setText(titleStr);&nbsp; &nbsp; return view;}// ...如果我期望有问题的数据库值会发生变化(例如,用户在设置中更新他们的用户名),那么我可能还希望使用某些生命周期方法,这些方法会在 Fragment (或 Activity)在暂停后恢复时触发,但是没有完全重建。// ...@overridepublic void onResume() {&nbsp; &nbsp; titleStr = "Username: " + model.getName();&nbsp; &nbsp; titleView.setText(titleStr);}// ...如果您不熟悉Android Activity 生命周期,这里有一个链接,这里是Fragments的一个很好的概要。希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java