如何在 ListView 中设置我的 TextView 和按钮图像的样式

How to style my TextView and Button Image Inside ListView

我想制作一个应用程序,其中包含我从 sqlite 预填充数据库中获得的引述和作者列表

我想做这样的东西

所以在左边,我有 2 个文本视图(1 个用于引用,另一个用于作者)

在右侧,有一个图像按钮,每次我单击时,心形图像都会从灰色变为红色,如果再次单击它,它就会从红色变为灰色

我已经用数据库填充了我的列表视图,使用来自另一个 xml 的 2 个文本视图和 1 个图像按钮。但我不知道如何设置字体样式并在单击时更改图像

这是我的代码

DatabaseOpenHelper.java

public class DatabaseOpenHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "mqn.db";
private static final int DATABASE_VERSION = 1;

private static final String TABLE_NAME = "quote";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_QUOTES = "quotesText";
public static final String COLUMN_AUTHOR= "author";
public static final String COLUMN_FAV = "fav";

private SQLiteDatabase database;

private final Context context;

// database path
private static String DATABASE_PATH;

/** constructor */
public DatabaseOpenHelper(Context ctx) {
    super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = ctx;
    DATABASE_PATH = context.getFilesDir().getParentFile().getPath()
            + "/databases/";

}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public void create() throws IOException {
    boolean check = checkDataBase();

    SQLiteDatabase db_Read = null;

    // Creates empty database default system path
    db_Read = this.getWritableDatabase();
    db_Read.close();
    try {
        if (!check) {
            copyDataBase();
        }
    } catch (IOException e) {
        throw new Error("Error copying database");
    }
}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 *
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DATABASE_PATH + DATABASE_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
        // database does't exist yet.
    }

    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException {

    // Open your local db as the input stream
    InputStream myInput = context.getAssets().open(DATABASE_NAME);

    // Path to the just created empty db
    String outFileName = DATABASE_PATH + DATABASE_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

/** open the database */
public void open() throws SQLException {
    String myPath = DATABASE_PATH + DATABASE_NAME;
    database = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);
}

/** close the database */
@Override
public synchronized void close() {
    if (database != null)
        database.close();
    super.close();
}

// insert a user into the database
public long insertUser(String quotesText, String author, String fav) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(COLUMN_QUOTES, quotesText );
    initialValues.put(COLUMN_AUTHOR, author);
    initialValues.put(COLUMN_FAV, fav);
    return database.insert(TABLE_NAME, null, initialValues);
}

// updates a user
public boolean updateUser(long rowId, String quotesText, String author,
                          String fav) {
    ContentValues args = new ContentValues();
    args.put(COLUMN_QUOTES, quotesText);
    args.put(COLUMN_AUTHOR, author);
    args.put(COLUMN_FAV, fav);
    return database.update(TABLE_NAME, args, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieves a particular user
public Cursor getUser(long rowId) throws SQLException {
    Cursor mCursor = database.query(true, TABLE_NAME, new String[] {
                    COLUMN_ID, COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV },
            COLUMN_ID + " = " + rowId, null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }

    return mCursor;
}

// delete a particular user
public boolean deleteContact(long rowId) {
    return database.delete(TABLE_NAME, COLUMN_ID + "=" + rowId, null) > 0;
}

// retrieves all users
public Cursor getAllUsers() {
    return database.query(TABLE_NAME, new String[] { COLUMN_ID,
                    COLUMN_QUOTES, COLUMN_AUTHOR, COLUMN_FAV }, null, null,
            null, null, null);
}

@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

}

QuotesActivity.java

public class QuotesActivity extends AppCompatActivity {

TextView title;
Typeface myFont;
ListView quotesList;
ListView favLV;
DatabaseOpenHelper myDbHelper;
DatabaseAccess databaseAccess;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quotes);

    myDbHelper = new DatabaseOpenHelper(this);

    try {
        // check if database exists in app path, if not copy it from assets
        myDbHelper.create();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    try {
        // open the database
        myDbHelper.open();
        myDbHelper.getWritableDatabase();
    } catch (SQLException sqle) {
        throw sqle;
    }

    populateListView();



    Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
    toolbar.setNavigationIcon(R.drawable.back_button);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    title = (TextView) findViewById(R.id.titleQuote);
    myFont =  Typeface.createFromAsset(getAssets(), "Montserrat-Bold.otf");
    title.setTypeface(myFont);
    title.setTextSize(20);
    title.setTextColor(Color.rgb(240, 239, 223));

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

private void populateListView() {
    Cursor cursor = myDbHelper.getAllUsers();
    String[] from = new String[] {myDbHelper.COLUMN_QUOTES, myDbHelper.COLUMN_AUTHOR};
    int[] to = new int[] {R.id.quoteLV, R.id.authorLV};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.quotes_listview, cursor, from, to,0);
    quotesList = (ListView) findViewById(R.id.quotesList);
    quotesList.setAdapter(myCursorAdapter);
}
}

Content_quotes.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="hendrasetiawan.mqn.QuotesActivity"
tools:showIn="@layout/activity_quotes">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/quotesList"
            android:layout_gravity="right"
            android:layout_weight="1" />

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/favList"
            android:layout_weight="6" />


    </LinearLayout>



</LinearLayout>
</LinearLayout>

quotes_listview.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/quoteLV"
    android:textSize="20dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/authorLV"
    android:textSize="20dp"/>
</LinearLayout>

每次我尝试设置字体大小/更改引号中的字体 Activity 我总是在空对象引用 android 上得到 错误

编辑POST

我的LogCat

(注意=我的quoteLV和authorLV现在是text1和text2) 我试着把 text1.setTextSize(50);在 populateView()

03-23 17:23:30.621 26550-26550/? I/art:延迟启用 -Xcheck:jni 03-23 17:23:30.659 26550-26550/hendrasetiawan.mqn W/System: ClassLoader 引用未知路径: /data/app/hendrasetiawan.mqn-1/lib/arm 03-23 17:23:30.953 26550-26590/hendrasetiawan.mqn D/OpenGLRenderer: 使用 EGL_SWAP_BEHAVIOR_PRESERVED: true 03-23 17:23:30.996 26550-26590/hendrasetiawan.mqn I/Adreno-EGL: : QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb 03-23 17:23:30.999 26550-26590/hendrasetiawan.mqn I/OpenGLRenderer:初始化 EGL,版本 1.4 03-23 17:23:32.201 26550-26550/hendrasetiawan.mqn I/SQLiteAssetHelper:成功打开数据库mqn.db 03-23 17:23:32.205 26550-26550/hendrasetiawan.mqn I/SQLiteAssetHelper:成功打开数据库mqn.db 03-23 17:23:32.216 26550-26550/hendrasetiawan.mqn D/AndroidRuntime: 关闭虚拟机 03-23 17:23:32.217 26550-26550/hendrasetiawan.mqn E/AndroidRuntime:致命异常:main 进程:hendrasetiawan.mqn,PID:26550 java.lang.RuntimeException: 无法启动 activity ComponentInfo{hendrasetiawan.mqn/hendrasetiawan.mqn.QuotesActivity}: java.lang.NullPointerException: 尝试在 null 上调用虚拟方法 'void android.widget.TextView.setTextSize(float)'对象引用 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 由以下原因引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法 'void android.widget.TextView.setTextSize(float)' 在 hendrasetiawan.mqn.QuotesActivity.populateListView(QuotesActivity.java:83) 在 hendrasetiawan.mqn.QuotesActivity.onCreate(QuotesActivity.java:78) 在 android.app.Activity.performCreate(Activity.java:6251) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 03-2317:28:32.266 26550-26550/hendrasetiawan.mqnI/Process:发送信号。 PID:26550 SIG:9

新编辑POST

content_quotes.xml

这里我只有 1 个 ListView

inside_listview.xml

这里有 2 个 textView 和 1 个 ButtonImage

引用Activity

本java、SetContentViewcontent_quotes.xml 所以当我为 content_quotes.xml 中的所有内容设置样式时,我可以轻松完成

现在,我从数据库中获取所有引语和作者 到 2 个文本视图(即 inside_listview.xml)

每次我尝试为它设置 2 个文本视图的样式时,我总是遇到错误 是因为它来自另一个 XML ??

为最喜欢的图像按钮设置样式:

我还没有看到你的代码。你说你已经填充了你的列表视图并且你的项目有两个文本视图和一个图像按钮。 从图像按钮更改为复选框,因此将心形按钮变成红色和灰色会很容易。

在您的 item.xml 中有这样的复选框。

 <CheckBox
    android:layout_margin="8dp"
    android:layout_gravity="right|top"
    android:button="@null"
    android:id="@+id/id_homeListing_fav"
    android:drawableTop="@drawable/fav"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

注意 drawableTop 标签指向 fav.xml 文件,在您的 fav.xml 文件中指定不同状态的可绘制对象,例如选中和未选中

注意按钮标签是空的

代码 fav.xml

<?xml version="1.0" encoding="utf-8"?>
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:drawable="@drawable/ic_fav_primary" android:state_checked="true"></item>
     <item android:drawable="@drawable/ic_fav_gray" android:state_checked="false"
    />

在上面fav.xml ic_fav_primary 是你的红色图标,另一个是灰色图标。

然后将 SetOnChangeListner 设置为复选框并执行相应的操作。

以及自定义文本字体See this Link

要更改字体:

  1. 从互联网上下载您要使用的字体。这似乎与您的图像几乎相同:http://www.fontspring.com/fonts/typoforge-studio/cervo?utm_source=fontsquirrel.com&utm_medium=matcherator_link&utm_campaign=cervo
  2. 创建一个 src/main/assets/fonts/ 文件夹
  3. 将下载的ttfotf字体文件移动到文件夹
  4. 应用下载的字体:
    Typeface type = Typeface.createFromAsset(getAssets(),"fonts/Kokila.ttf"); txtyour.setTypeface(type);

单击布局后更改图像

yourTextView.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
          yourImageView.setImageDrawable(R.drawable.image);
     }
});

向 TextView 和 ImageView 添加一些填充

android:padding="8dp"

这应该让您了解如何设置布局样式