【发布时间】:2015-03-05 13:20:50
【问题描述】:
我有一个由ListView 和TextView 组成的Fragment。 ListView 包含几个TextView,通过自定义SimpleCursorAdapter 和CursorLoader 从数据库加载数值。所以这些值在显示后是静态的。我想对值求和并在单独的 TextView 中直接显示总数。
我该怎么做?我的意思是从用户的角度来看,列表和总数必须同时显示。我可以使用额外的加载器单独获取总数,但我想避免这种情况。那么我应该把求和逻辑放在哪一点呢?
我有一个这样的查询,其中每一行都会为 listView 填充一个项目:
SELECT group_name, group_amount FROM notes;
我不想执行如下单独的查询来计算总量,如果可能的话,我想从 GUI 中安全地获取它
SELECT sum(group_amount) FROM notes;
这是我的代码:
创建视图上的片段
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.monthly_report, container, false);
ListView listCosts = (ListView)rootView.findViewById(R.id.list_costs);
costsAdapter = new VehReportAdapter(getActivity(),
com.vortexalex.vehnotes.R.layout.monthly_report_single_item, null,
VehReportAdapter.fromColumns, toViews, 0);
listCosts.setAdapter(costsAdapter);
}
片段 onActivityCreated
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(VehTabsUtil.REPORT_COSTS_LOADER_ID, null, (LoaderCallbacks<Cursor>) this);
}
加载器已完成的片段
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
costsAdapter.swapCursor(cursor);
}
适配器绑定视图(适配器extends SimpleCursorAdapter)
public void bindView(View view, Context context, Cursor cursor) {
Integer dbAmount = cursor.getInt(cursor.getColumnIndex(AccountingContract.Report.COLUMN_NAME_GROUP_AMOUNT));
String amount = NumberUtil.formatAmount(dbAmount);
((TextView) view.findViewById(com.vortexalex.vehnotes.R.id.report_item_amount)).setText(amount);
}
片段布局 montly_report.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="vertical"
android:padding="6dip" >
<ListView android:id="@+id/list_costs"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="2"
android:drawSelectorOnTop="false"/>
<TextView
android:id="@+id/costs_sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start"
android:padding="6dip"
/>
</LinearLayout>
【问题讨论】:
-
什么值?列表中的项目总数?
-
@Apurva 不,它们代表金额
-
我用关于 SQL 查询的新细节编辑了我的帖子
-
同时发布您的数据库助手代码
-
我不认为发布简单的帮助代码很有用。 “查询”部分运行良好。我刚刚实现了
Loader.loadOnBackground方法,它调用了助手并返回了Cursor。
标签: java android android-listview simplecursoradapter