我正在使用列表。想要更改项目中的字体。标题文本视图和描述。所有视图都在适配器中初始化,它们是最终的。从CursorAdapter扩展的适配器就是为什么我不能使用getAssets方法。
那么如果我从CursorAdapter扩展但是同时我需要将AppCombat方法用作getAssets,我应该怎么做?
主要活动:
public class CatalogActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = "myLogs";
/** Identifier for the pet data loader */
private static final int LIST_LOADER = 0;
/** Adapter for the ListView */
ListCursorAdapter mCursorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
// Changing font
Log.v(TAG, "--- WE ARE IN CATALOG ACTIVITY ---");
// Setup FAB to open EditorActivity
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
// Find the ListView which will be populated with the list data
ListView listListView = (ListView) findViewById(R.id.list);
// Find and set empty view on the ListView, so that it only shows when the list has 0 items.
View emptyView = findViewById(R.id.empty_view);
listListView.setEmptyView(emptyView);
// Setup an Adapter to create a list item for each row of list data in the Cursor.
// There is no items data yet (until the loader finishes) so pass in null for the Cursor.
mCursorAdapter = new ListCursorAdapter(this, null);
listListView.setAdapter(mCursorAdapter);
// Setup the item click listener
listListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
ShoppingListBdHelper helper = new ShoppingListBdHelper(view.getContext());
if (helper.setCompleted(id)) {
mCursorAdapter.setCompleted(view);
}
}
});
// Kick off the loader
getSupportLoaderManager().initLoader(LIST_LOADER, null, this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_catalog.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
switch (item.getItemId()) {
// Respond to a click on the "Insert dummy data" menu option
case R.id.action_share_button:
shareButton(mCursorAdapter.getCursor());
return true;
// Respond to a click on the "Delete all entries" menu option
case R.id.action_delete_all_entries:
deleteAllItems();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Share button
*/
private void shareButton(Cursor cursor) {
Log.v(TAG, "--- WE ARE IN SHARE BUTTON METHOD ---");
List<String> test;
test = new ArrayList<String>();
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Log.d(TAG, "field: " + cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME)));
test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_NAME)) + " - " + cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION))); //add the item
// test.add(cursor.getString(cursor.getColumnIndex(ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION))); //add the item
cursor.moveToNext();
}
cursor.moveToFirst();
cursor.close();
// for (String comma : )
Log.v(TAG, "--- OUR LIST INCLUDES: " + test.toString());
Intent myIntent = new Intent();
myIntent.setAction(Intent.ACTION_SEND);
myIntent.putStringArrayListExtra("test", (ArrayList<String>) test);
myIntent.putExtra(android.content.Intent.EXTRA_TEXT, test.toString());
Log.v(TAG, "--- INTENT EXTRAS ARE: " + myIntent.getExtras());
myIntent.setType("text/plain");
startActivity(Intent.createChooser(myIntent, "Share using"));
}
/**
* Helper method to delete all list in the database.
*/
private void deleteAllItems() {
Log.v(TAG, "Сработал метод удаления всех данных");
long rowsDeleted = getContentResolver().delete(ListContract.ListEntry.CONTENT_URI, null, null);
Log.v("CatalogActivity", rowsDeleted + " rows deleted from list database");
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
Log.v(TAG, "Начал работать loader cursor");
// Define a projection that specifies the columns from the table we care about.
String[] projection = {
ListContract.ListEntry._ID,
ListContract.ListEntry.COLUMN_ITEM_NAME,
ListContract.ListEntry.COLUMN_ITEM_DESCRIPTION,
ListContract.ListEntry.COLUMN_ITEM_COMPLETED
};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this, // Parent activity context
ListContract.ListEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Update {@link ListCursorAdapter} with this new cursor containing updated pet data
mCursorAdapter.swapCursor(data);
Log.v(TAG, "Cursor adapter загрузился");
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// Callback called when the data needs to be deleted
mCursorAdapter.swapCursor(null);
}
}
列出适配器
@Override
public void bindView(View view, Context context, final Cursor cursor) {
// Find individual views that we want to modify in the list item layout
final TextView nameTextView = (TextView) view.findViewById(R.id.name);
final TextView summaryTextView = (TextView) view.findViewById(R.id.summary);
Typeface titleTypeface = Typeface.createFromAsset(getAssets(), "Roboto-Regular.ttf");
Typeface descriptionTypeface = Typeface.createFromAsset(getAssets(), "OpenSans-Italic.ttf");
Log.v(TAG, "--- FONT IS ---" + titleTypeface );
nameTextView.setTypeface(titleTypeface);
summaryTextView.setTypeface(descriptionTypeface);
// Find the columns of pet attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(ListEntry.COLUMN_ITEM_NAME);
int breedColumnIndex = cursor.getColumnIndex(ListEntry.COLUMN_ITEM_DESCRIPTION);
// Read the pet attributes from the Cursor for the current pet
String petName = cursor.getString(nameColumnIndex);
String petBreed = cursor.getString(breedColumnIndex);
// If the pet breed is empty string or null, then use some default text
// that says "Unknown breed", so the TextView isn't blank.
if (TextUtils.isEmpty(petBreed)) {
petBreed = context.getString(R.string.unknown_description);
}
// Update the TextViews with the attributes for the current pet
nameTextView.setText(petName);
summaryTextView.setText(petBreed);
view.findViewById(R.id.editImageView).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v(TAG, "--- WE ARE IN IMAGEVIEW LISTENER ---");
Intent intent = new Intent(v.getContext(), EditorActivity.class);
// Form the content URI that represents the specific pet that was clicked on,
// by appending the "id" (passed as input to this method) onto the
// {@link PetEntry#CONTENT_URI}.
// For example, the URI would be "content://com.example.android.pets/pets/2"
// if the pet with ID 2 was clicked on.
Uri currentPetUri = ContentUris.withAppendedId(
ListContract.ListEntry.CONTENT_URI,
cursor.getInt(cursor.getColumnIndex(ListEntry._ID))
);
Log.v(TAG, "--- CONTENT URI " + cursor.getInt(cursor.getColumnIndex(ListEntry._ID)));
// Set the URI on the data field of the intent
intent.setData(currentPetUri);
// Launch the {@link EditorActivity} to display the data for the current pet.
v.getContext().startActivity(intent);
}
}
);
view.findViewById(R.id.leftSide).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v(TAG, "--- WE ARE IN LEFTSIDE LISTENER ---");
//
// Intent intent = new Intent(v.getContext(), EditorActivity.class);
//
// // Form the content URI that represents the specific pet that was clicked on,
// // by appending the "id" (passed as input to this method) onto the
// // {@link PetEntry#CONTENT_URI}.
// // For example, the URI would be "content://com.example.android.pets/pets/2"
// // if the pet with ID 2 was clicked on.
// Uri currentPetUri = ContentUris.withAppendedId(
// ListContract.ListEntry.CONTENT_URI,
// cursor.getInt(cursor.getColumnIndex(ListEntry._ID))
// );
//
// // Set the URI on the data field of the intent
// intent.setData(currentPetUri);
//
// // Launch the {@link EditorActivity} to display the data for the current pet.
// v.getContext().startActivity(intent);
nameTextView.setPaintFlags(nameTextView.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
summaryTextView.setPaintFlags(summaryTextView.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
}
}
);
Boolean completed = cursor.getInt(cursor.getColumnIndex(ListEntry.COLUMN_ITEM_COMPLETED)) == 1;
if (completed) {
setCompleted(view);
}
}
错误类型2
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.list, PID: 10811
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.list/com.example.android.list.CatalogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
at com.example.android.list.CatalogActivity.onCreate(CatalogActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)