其他分享
首页 > 其他分享> > Android Studio里面simple_list_item_2设置两行文本的字体大小和颜色

Android Studio里面simple_list_item_2设置两行文本的字体大小和颜色

作者:互联网

我看到网上说,android.R.layout.simple_list_item_2里面的文本字体是无法自定义的,要自定义的话必须要自己新建一个layout xml,或者自己重新定义一个Adapter类。
但实际上这种说法是错误的,想要修改simple_list_item_2里面的文本字体非常简单!

package com.oct1158.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextPaint;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    private ArrayList<HashMap<String, String>> deviceList = new ArrayList<HashMap<String, String>>();
    private ListView listView;
    private SimpleAdapter simpleAdapter;

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

        listView = findViewById(R.id.listView);
        String[] keys = {"name", "desc"};
        int[] ids = {android.R.id.text1, android.R.id.text2};
        simpleAdapter = new SimpleAdapter(this, deviceList, android.R.layout.simple_list_item_2, keys, ids) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);

                // 设置第一行字体颜色和大小
                TextView text1 = view.findViewById(android.R.id.text1);
                text1.setTextColor(Color.BLUE);
                text1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
                // 第一行字体加粗
                TextPaint tp = text1.getPaint();
                tp.setFakeBoldText(true);

                // 设置第二行字体颜色和大小
                TextView text2 = view.findViewById(android.R.id.text2);
                text2.setTextColor(Color.GREEN);
                text2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);

                return view;
            }
        };
        listView.setAdapter(simpleAdapter);

        HashMap<String, String> info = new HashMap<String, String>();
        info.put("name", "不错过");
        info.put("desc", "要错过");
        deviceList.add(info);
        info = new HashMap<String, String>();
        info.put("name", "Hello World");
        info.put("desc", "嘿嘿嘿");
        deviceList.add(info);
        simpleAdapter.notifyDataSetChanged();
    }
}

这不就修改成功了吗!

标签:info,字体大小,simple,list,text2,text1,import,android,view
来源: https://blog.csdn.net/ZLK1214/article/details/119409136