如何在代码中为组件设置dip,sp值

本文详细介绍了在Android应用开发中如何正确地为TextView和ImageView等组件设置字体大小及宽高尺寸,包括使用sp、dp单位确保跨设备一致性,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android 中textview一类的组件设定字体大小,,width,height都是在xml中设置,这个当然大家都是知道的,不过呢咱这里就当复习复习基础了

一.我们先看看要给一个Textview设置大小是16sp/dp/dip该如何做呢?

在android中为一个TextView组件设定字体大小是很容易的,android推荐使用sp作为文字显示的大小单位,因此为一个Textview设置字体大小有以下方式

1.android:textSize="16sp";或者android:textSize="@dimen/txt_size_16"(在values文件夹下中dimens.xml的定义<dimen name="txt_size_16">16sp</dimen>)

2.(假设已定义TextView实例tview)tview.setTextSize(16)或者tview.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

  
  1. 此处以TextView为例: 
  2. 创建一个TextView实例 
  3. TextView tview=new TextView(this); 
  4. Api中设置字体大小的方法 
  5. tview.setTextSize(int unit, float size); 
  6. tview.setTextSize(float size); 

注意:上述列子中TextView的文字最终显示的大小是相同的。tview的setTexView方法就是设置的scaled pixel大小的值,参见api描述: Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.

二.若是在代码中为组件dp/sp宽高尺寸呢?

在xml中指定组件的宽高很容易,可以使用px,dip(dp),sp等,android推荐使用dp/dip。由于android分辨率和显示屏物理尺寸的差异。我们知道很多时候我们可能需要动态添加一些组件,并为这些组件指定大小,这个大小又还必须在不同分辨率不同尺寸的设备下显示较好的几乎一致的效果,我们该怎么办呢?我想肯定会想着去设置dp/dip/sp值,那么到底如何去设置呢?

我自己有以下方法:

方法:通过查api,我们知道在android内部会使用TypedValue.applyDimension函数将所有单位(sp/dp/dip等)换算成px,所以我们的方法与此有关,首先看看这个转换的方法

 

  
  1. public static float applyDimension(int unit, float value, 
  2.                                    DisplayMetrics metrics) 
  3.     switch (unit) { 
  4.     case COMPLEX_UNIT_PX: 
  5.         return value; 
  6.     case COMPLEX_UNIT_DIP: 
  7.         return value * metrics.density; 
  8.     case COMPLEX_UNIT_SP: 
  9.         return value * metrics.scaledDensity; 
  10.     case COMPLEX_UNIT_PT: 
  11.         return value * metrics.xdpi * (1.0f/72); 
  12.     case COMPLEX_UNIT_IN: 
  13.         return value * metrics.xdpi; 
  14.     case COMPLEX_UNIT_MM: 
  15.         return value * metrics.xdpi * (1.0f/25.4f); 
  16.     } 
  17.     return 0; 

所以我们的实现方法当然与此有关了,下面是代码部分:

home.xml

  
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  2.     android:layout_width="fill_parent" 
  3.     android:layout_height="fill_parent" 
  4.     android:orientation="vertical" > 
  5.  
  6.     <TextView 
  7.         android:id="@+id/textView1" 
  8.         android:layout_width="wrap_content" 
  9.         android:layout_height="wrap_content" 
  10.         android:text="xml中以dp为单位显示" /> 
  11.  
  12.     <ImageView 
  13.         android:id="@+id/imageView1" 
  14.         android:layout_width="100dip" 
  15.         android:layout_height="100dip" 
  16.         android:layout_marginTop="10dp" 
  17.         android:src="@drawable/a11" /> 
  18.  
  19.     <TextView 
  20.         android:id="@+id/textView2" 
  21.         android:layout_width="wrap_content" 
  22.         android:layout_height="wrap_content" 
  23.         android:layout_marginTop="14dp" 
  24.         android:text="代码动态添加值" /> 
  25.  
  26.     <ImageView 
  27.         android:id="@+id/imageView2" 
  28.         android:layout_width="wrap_content" 
  29.         android:layout_height="wrap_content" 
  30.         android:layout_marginTop="10dp" 
  31.         android:src="@drawable/a11" /> 
  32.  
  33. </LinearLayout> 

 

HomeActivity.java

 

  
  1. package com.example.aboutexpand; 
  2.  
  3. import android.app.Activity; 
  4. import android.content.Context; 
  5. import android.content.res.Resources; 
  6. import android.os.Bundle; 
  7. import android.util.TypedValue; 
  8. import android.view.ViewGroup.LayoutParams; 
  9. import android.widget.ImageButton; 
  10. import android.widget.ImageView; 
  11. import android.widget.LinearLayout; 
  12. import android.widget.RelativeLayout; 
  13. import android.widget.TextView; 
  14.  
  15. public class HomeActivity extends Activity { 
  16.     private ImageView imgView1 = null;// xml布局中定义大小宽高为100dip 
  17.     private ImageView imgView2 = null;// 需要动态设置大小,也要为100dip 
  18.     ImageButton imgBtn = null
  19.  
  20.     @Override 
  21.     protected void onCreate(Bundle savedInstanceState) { 
  22.  
  23.         super.onCreate(savedInstanceState); 
  24.         setContentView(R.layout.home); 
  25.         imgView1 = (ImageView) findViewById(R.id.imageView1); 
  26.         int img1H = imgView1.getDrawable().getIntrinsicHeight(); 
  27.         int img1W = imgView1.getDrawable().getIntrinsicWidth(); 
  28.  
  29.         imgView2 = (ImageView) findViewById(R.id.imageView2); 
  30.         // 方法一 
  31.         // imgView2.setLayoutParams(new LinearLayout.LayoutParams( 
  32.         // (int) getRawSize(TypedValue.COMPLEX_UNIT_DIP, 100), 
  33.         // (int) getRawSize(TypedValue.COMPLEX_UNIT_DIP, 100))); 
  34.         // 方法二 
  35.         imgView2.setLayoutParams(new LinearLayout.LayoutParams( 
  36.                 getIntFromDimens(R.dimen.img_height), 
  37.                 getIntFromDimens(R.dimen.img_widthe))); 
  38.  
  39.         int img2H = imgView2.getDrawable().getIntrinsicHeight(); 
  40.         int img2W = imgView2.getDrawable().getIntrinsicWidth(); 
  41.         TextView tview1 = (TextView) findViewById(R.id.textView1); 
  42.         tview1.getText(); 
  43.         tview1.setText(tview1.getText() + "图片h" + img1H + "w" + img1W); 
  44.         TextView tview2 = (TextView) findViewById(R.id.textView2); 
  45.         tview2.setText(tview2.getText() + "图片h" + img2H + "w" + img2W); 
  46.     } 
  47.  
  48.     // 方法一 
  49.     public float getRawSize(int unit, float value) { 
  50.         Resources res = this.getResources(); 
  51.         return TypedValue.applyDimension(unit, value, res.getDisplayMetrics()); 
  52.     } 
  53.  
  54.     // 方法2,需先在values中dimens的进行设置 
  55.     public int getIntFromDimens(int index) { 
  56.         int result = this.getResources().getDimensionPixelSize(index); 
  57.         return result; 
  58.     } 
  59.  
for (int i = 0;i < dataLists.size();i++) { DataList.DataDTO 数据 = dataLists.get(i).getData(); List<DataList.DataDTO.ComponentsDTO> components = data.getComponents(); for (int j = 0;j < components.size();j++) { 字符串名称 = components.get(j).getName(); 类型 = components.get(j).getType(); Log.i(“组件:”, “” + 类型); setStyle = components.get(j).getSetStyle(); Log.i(“组件:”, 名称); //1文本组件 2图片组件 3视频组件 4天气 5日期 6线路 if (type == 1) { int 度 = setStyle.getHeight(); int width = setStyle.getWidth(); int left = setStyle.getLeft(); int top = setStyle.getTop(); int marqueeWidth = Integer.parseInt(String.valueOf(width)); int marqueeHeight = Integer.parseInt(String.valueOf(height)); int marqueeTop = Integer.parseInt(String.valueOf(top)); Log.i(“aaaaaaa”, “文本组件marqueeTop:” + marqueeTop); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvMarquee.getLayoutParams(); params.width = dip2px(MainActivity.this, marqueeWidth); params.height = dip2px(MainActivity.this, marqueeHeight); params.leftMargin = dip2px(MainActivity.this, 左);// 设置左边距 params.topMargin = dip2px(MainActivity.this, marqueeTop);// 设置上边距 Log.i(“aaaaaaa”, “文本组件:” + type); } else if (type == 2) { int 度 = setStyle.getHeight(); int width = setStyle.getWidth(); int left = setStyle.getLeft(); int top = setStyle.getTop(); int imageWidth = Integer.parseInt(String.valueOf(width)); int imageHeight = Integer.parseInt(String.valueOf(height)); int imageTop = Integer.parseInt(String.valueOf(top)); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvImage.getLayoutParams(); params.width = dip2px(MainActivity.this, imageWidth); params.height = dip2px(MainActivity.this, imageHeight); params.leftMargin = dip2px(MainActivity.this, left);// 设置左边距 params.topMargin = dip2px(MainActivity.this, imageTop);// 设置上边距 Log.i(“aaaaaaa”, “图片组件:” + type); } else if (type == 3) { int 度 = setStyle.getHeight(); int width = setStyle.getWidth(); int left = setStyle.getLeft(); int top = setStyle.getTop(); int videoWidth = Integer.parseInt(String.valueOf(width)); int videoHeight = Integer.parseInt(String.valueOf(height)); int videoTop = Integer.parseInt(String.valueOf(top)); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvVideo.getLayoutParams(); params.width = dip2px(MainActivity.this, videoWidth); params.height = dip2px(MainActivity.this, videoHeight); params.leftMargin = dip2px(MainActivity.this, left);// 设置左边距 params.topMargin = dip2px(MainActivity.this, videoTop);// 设置上边距 Log.i(“aaaaaaa”, “视频组件:” + type); } else if (type == 4) { int 度 = setStyle.getHeight(); int width = setStyle.getWidth(); int left = setStyle.getLeft(); int top = setStyle.getTop(); int weatherWidth = Integer.parseInt(String.valueOf(width)); int weatherHeight = Integer.parseInt(String.valueOf(height)); int weatherTop = Integer.parseInt(String.valueOf(top)); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvWeather.getLayoutParams(); params.width = dip2px(MainActivity.this, weatherWidth); params.height = dip2px(MainActivity.this, weatherHeight); params.leftMargin = dip2px(MainActivity.this, left);// 设置左边距 params.topMargin = dip2px(MainActivity.this, weatherTop);// 设置上边距 Log.i(“aaaaaaa”, “天气组件:” + type); } else if (type == 5) { int 度 = setStyle.getHeight(); int width = setStyle.getWidth(); int left = setStyle.getLeft(); int top = setStyle.getTop(); int dateWidth = Integer.parseInt(String.valueOf(width)); int dateHeight = Integer.parseInt(String.valueOf(height)); int dateTop = Integer.parseInt(String.valueOf(top)); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvDate.getLayoutParams(); params.width = dip2px(MainActivity.this, dateWidth); params.height = dip2px(MainActivity.this, dateHeight); params.leftMargin = dip2px(MainActivity.this, left);// 设置左边距 params.topMargin = dip2px(MainActivity.this, dateTop);// 设置上边距 Log.i(“aaaaaaa”, “日期组件:” + type); } else if (type == 6) { int 度 = setStyle.getHeight(); int width = setStyle.getWidth(); int left = setStyle.getLeft(); int top = setStyle.getTop(); int listWidth = Integer.parseInt(String.valueOf(width)); int listHeight = Integer.parseInt(String.valueOf(height)); int listTop = Integer.parseInt(String.valueOf(top)); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvList.getLayoutParams(); params.width = dip2px(MainActivity.this, listWidth); params.height = dip2px(MainActivity.this, listHeight); params.leftMargin = dip2px(MainActivity.this, left);// 设置左边距 params.topMargin = dip2px(MainActivity.this, listTop);// 设置上边距 Log.i(“aaaaaaa”, “线路组件:” + type); } } } <?xml 版本=“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:orientation=“vertical” tools:context=“ 的MainActivity”> <TextView android:id=“@+id/文本” android:layout_width=“wrap_content” 安卓:layout_height=“wrap_content” android:text=“1.0” android:textSize=“30sp” 安卓:layout_gravity=“center” android:visibility=“gone” /> <TextView android:id=“@+id/tv_marquee” android:layout_width=“match_parent” 安卓:layout_height=“50dp” android:background=“@color/黑色” android:text=“跑马灯” android:textColor=“@color/白色” android:textSize=“30sp” android:gravity=“center” /> <TextView android:id=“@+id/tv_video” android:layout_width=“match_parent” 安卓:layout_height=“260dp” android:background=“@color/select_color” android:text=“视频” android:gravity=“center” android:textColor=“@color/白色” android:textSize=“30sp” /> <LinearLayout android:layout_width=“match_parent” 安卓:layout_height=“wrap_content” android:orientation=“horizontal” <TextView android:id=“@+id/tv_date” 安卓:layout_width=“0dp” 安卓:layout_height=“50dp” 安卓:layout_weight=“1” android:background=“@color/common_botton_bar_blue” android:text=“时间日期” android:textColor=“@color/白色” android:gravity=“center” android:textSize=“30sp” /> <TextView android:id=“@+id/tv_weather” 安卓:layout_width=“0dp” 安卓:layout_height=“50dp” android:background=“@color/time_bg” 安卓:layout_weight=“1” android:text=“天气” android:textColor=“@color/白色” android:gravity=“center” android:textSize=“30sp” /> </LinearLayout> <TextView android:id=“@+id/tv_list” android:layout_width=“match_parent” android:layout_height=“match_parent” android:background=“@color/colorPrimary” android:text=“列表” android:textColor=“@color/白色” android:gravity=“center” android:textSize=“30sp” /> </LinearLayout>这段代码根据获取的实现所有控件可以随便调换位置,怎么修改
最新发布
06-29
package com.example.kucun2.ui.dingdan;//package com.example.kucun2; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.HorizontalScrollView; import android.widget.LinearLayout; import android.widget.SearchView; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import com.example.kucun2.R; import com.example.kucun2.View.HorizontalScrollTextView; import com.example.kucun2.entity.Bancai; import com.example.kucun2.entity.Chanpin; import com.example.kucun2.entity.Chanpin_Zujian; import com.example.kucun2.entity.Dingdan; import com.example.kucun2.entity.Dingdan_Bancai; import com.example.kucun2.entity.Dingdan_Chanpin; import com.example.kucun2.entity.data.Data; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class OrderDisplayFragment extends Fragment { private TableLayout table; private HorizontalScrollView horizontalScrollView; private ValueAnimator scrollIndicatorAnimator; private boolean isIndicatorVisible = false; // 添加排序相关的成员变量 private int currentSortColumn = -1; private boolean sortAscending = true; private List<Object[]> allTableRowsData = new ArrayList<>(); // 添加搜索相关成员变量 private SearchView searchView; private Spinner columnSelector; private List<Object[]> filteredTableRowsData = new ArrayList<>(); /** *加载初始化 * @param inflater The LayoutInflater object that can be used to inflate * any views in the fragment, * @param container If non-null, this is the parent view that the fragment's * UI should be attached to. The fragment should not add the view itself, * but this can be used to generate the LayoutParams of the view. * @param savedInstanceState If non-null, this fragment is being re-constructed * from a previous saved state as given here. * * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_order_display, container, false); table = view.findViewById(R.id.orderTable); horizontalScrollView = view.findViewById(R.id.horizontalScrollContainer); View scrollIndicator = view.findViewById(R.id.scroll_indicator); // 获取搜索控件 searchView = view.findViewById(R.id.search_view); columnSelector = view.findViewById(R.id.column_selector); // 初始化表头选择器 initColumnSelector(); // 设置搜索监听 searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { applySearchFilter(); return true; } @Override public boolean onQueryTextChange(String newText) { applySearchFilter(); return true; } }); LinearLayout fixedSearchBar = view.findViewById(R.id.fixedSearchBar); View placeholder = view.findViewById(R.id.search_bar_placeholder); // 添加全局布局监听器以获取正确的搜索框度 fixedSearchBar.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // 获取搜索框的实际度 int searchBarHeight = fixedSearchBar.getHeight(); // 设置占位视图的度 ViewGroup.LayoutParams params = placeholder.getLayoutParams(); params.height = searchBarHeight; placeholder.setLayoutParams(params); // 确保仅运行一次 fixedSearchBar.getViewTreeObserver().removeOnGlobalLayoutListener(this); } } ); // 添加表头 addTableHeader(table); // 填充表格数据 fillTableData(); // 添加滚动监听 horizontalScrollView.getViewTreeObserver().addOnScrollChangedListener(() -> { int maxScroll = horizontalScrollView.getChildAt(0).getWidth() - horizontalScrollView.getWidth(); int currentScroll = horizontalScrollView.getScrollX(); if (currentScroll > 0 && maxScroll > 0) { if (!isIndicatorVisible) { showScrollIndicator(); } // 更新滚动指示器位置 updateScrollIndicatorPosition(currentScroll, maxScroll); } else { hideScrollIndicator(); } }); return view; } /** * 获取数据 */ private void fillTableData() { List<Dingdan> orders = Data.dingdans; List<Dingdan_Chanpin> orderProducts = Data.dingdanChanpins; List<Dingdan_Bancai> orderMaterials = Data.dingdanBancais; for (Dingdan order : orders) { for (Dingdan_Chanpin orderProduct : orderProducts) { if (orderProduct.getDingdan().getId().equals(order.getId())) { Chanpin product = orderProduct.getChanpin(); for (Chanpin_Zujian component : product.getZujians()) { for (Dingdan_Bancai material : orderMaterials) { // 创建行数据但不立即添加到表格 Object[] rowData = createRowData( order, product, component, material ); allTableRowsData.add(rowData); filteredTableRowsData.add(rowData); // if (material.getZujian() != null && // material.getZujian().getId().equals(component.getId())) { // // addTableRow(createRowData( // order, product, component, material // )); // } } } } } } // 初始排序 sortTableData(-1, true); // 初始显示原始顺序 } /** * 排序表格数据并刷新显示 * @param columnIndex 要排序的列索引 * @param ascending 是否升序排列 */ private void sortTableData(int columnIndex, boolean ascending) { // 更新排序状态 if (columnIndex >= 0) { if (currentSortColumn == columnIndex) { // 相同列点击时切换排序方向 sortAscending = !ascending; } else { currentSortColumn = columnIndex; sortAscending = true; // 新列默认升序 } } // 创建排序比较器 Comparator<Object[]> comparator = (row1, row2) -> { if (currentSortColumn < 0) { return 0; // 返回0表示相等,保持原顺序 } Object value1 = row1[currentSortColumn]; Object value2 = row2[currentSortColumn]; if (value1 == null && value2 == null) return 0; if (value1 == null) return -1; if (value2 == null) return 1; // 根据不同列数据类型定制比较规则 try { // 数列:2(数量), 5(板材/组件), 6(订购数量) if (currentSortColumn == 2 || currentSortColumn == 5 || currentSortColumn == 6) { double d1 = Double.parseDouble(value1.toString()); double d2 = Double.parseDouble(value2.toString()); return sortAscending ? Double.compare(d1, d2) : Double.compare(d2, d1); } // 其他列按字符串排序 else { String s1 = value1.toString().toLowerCase(); String s2 = value2.toString().toLowerCase(); return sortAscending ? s1.compareTo(s2) : s2.compareTo(s1); } } catch (NumberFormatException e) { // 解析失败时按字符串比较 String s1 = value1.toString().toLowerCase(); String s2 = value2.toString().toLowerCase(); return sortAscending ? s1.compareTo(s2) : s2.compareTo(s1); } }; // 刷新表格显示 Collections.sort(filteredTableRowsData, comparator); // 刷新显示 refreshTableWithData(filteredTableRowsData); } /** * 表格数据动态添加 * @param rowData */ private void addTableRow(Object[] rowData) { TableRow row = new TableRow(requireContext()); TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT ); row.setLayoutParams(rowParams); row.setMinimumHeight(dpToPx(36)); for (Object data : rowData) { HorizontalScrollTextView textView = new HorizontalScrollTextView(requireContext()); textView.setText(String.valueOf(data)); textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); int padding = dpToPx(8); textView.setPadding(padding, padding / 2, padding, padding / 2); textView.setMinWidth(dpToPx(50)); TableRow.LayoutParams colParams=null; // 设置背景边框 textView.setBackgroundResource(R.drawable.cell_border); if ( data.toString().length() > 10){ colParams = new TableRow.LayoutParams( 0, // 宽度将由权重控制 TableRow.LayoutParams.MATCH_PARENT, 2.0f ); colParams.weight = 2; }else{ colParams = new TableRow.LayoutParams( 0, // 宽度将由权重控制 TableRow.LayoutParams.MATCH_PARENT, 1.0f ); colParams.weight = 1; } textView.setLayoutParams(colParams); row.addView(textView); } table.addView(row); } // 动态添加表头 (使用自定义TextView) private void addTableHeader(TableLayout table) { TableRow headerRow = new TableRow(requireContext()); headerRow.setLayoutParams(new TableLayout.LayoutParams( TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT )); // 设置行背景颜色 headerRow.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.purple_500)); // 定义表头 String[] headers = getResources().getStringArray(R.array.table_headers); float[] weights = {1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 1.0f, 1.0f}; // 列宽优先级数组(板材信息列优先) boolean[] priority = {false, false, false, false, true, false, false}; for (int i = 0; i < headers.length; i++) { HorizontalScrollTextView headerView = new HorizontalScrollTextView(requireContext()); headerView.setText(headers[i]); headerView.setTextColor(Color.WHITE); headerView.setTypeface(null, Typeface.BOLD); headerView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16); headerView.setPadding(dpToPx(8), dpToPx(8), dpToPx(8), dpToPx(8)); // 为优先级的列设置最小宽度 if (priority[i]) { headerView.setMinWidth(dpToPx(200)); } // 设置布局参数 TableRow.LayoutParams colParams = new TableRow.LayoutParams( priority[i] ? TableRow.LayoutParams.WRAP_CONTENT : 0, TableRow.LayoutParams.MATCH_PARENT, priority[i] ? 0 : weights[i] // 优先级列不使用权重 ); headerView.setLayoutParams(colParams); final int columnIndex = i; headerView.setOnClickListener(v -> { // 排序并刷新表格 sortTableData(columnIndex, sortAscending); // 更新排序指示器(可选) showSortIndicator(headerView); }); headerRow.addView(headerView); } table.addView(headerRow); } // 添加排序指示器(可选) private void showSortIndicator(View header) { // 实现:在表头右侧添加↑或↓指示符 // 实现逻辑根据设计需求 // header.setTooltipText(new ); } /** * */ private void showScrollIndicator() { isIndicatorVisible = true; View indicator = getView().findViewById(R.id.scroll_indicator); if (scrollIndicatorAnimator != null && scrollIndicatorAnimator.isRunning()) { scrollIndicatorAnimator.cancel(); } indicator.setVisibility(View.VISIBLE); indicator.setAlpha(0f); scrollIndicatorAnimator = ObjectAnimator.ofFloat(indicator, "alpha", 0f, 0.8f); scrollIndicatorAnimator.setDuration(300); scrollIndicatorAnimator.start(); } /**+ * */ private void hideScrollIndicator() { isIndicatorVisible = false; View indicator = getView().findViewById(R.id.scroll_indicator); if (scrollIndicatorAnimator != null && scrollIndicatorAnimator.isRunning()) { scrollIndicatorAnimator.cancel(); } scrollIndicatorAnimator = ObjectAnimator.ofFloat(indicator, "alpha", indicator.getAlpha(), 0f); scrollIndicatorAnimator.setDuration(300); scrollIndicatorAnimator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { indicator.setVisibility(View.INVISIBLE); } }); scrollIndicatorAnimator.start(); } /** * * @param currentScroll * @param maxScroll */ private void updateScrollIndicatorPosition(int currentScroll, int maxScroll) { View indicator = getView().findViewById(R.id.scroll_indicator); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) indicator.getLayoutParams(); // 计算指示器位置(0-100%) float percentage = (float) currentScroll / maxScroll; int maxMargin = getResources().getDisplayMetrics().widthPixels - indicator.getWidth(); // 设置右边距(控制位置) params.rightMargin = (int) (maxMargin * percentage); indicator.setLayoutParams(params); } // DP转PX工具方法 private int dpToPx(int dp) { return (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics() ); } /** * 数据组合 * @param order * @param product * @param component * @param material * @return */ private Object[] createRowData(Dingdan order, Chanpin product, Chanpin_Zujian component, Dingdan_Bancai material) { Bancai board = material.getBancai(); String boardInfo = board.TableText(); ; return new Object[] { order.getNumber(), // 订单号 product.getId(), // 产品编号 "1", // 产品数量 (根据需求调整) component.getZujian().getName(), // 组件名 boardInfo, // 板材信息 Math.round(component.getOne_several()), // 板材/组件 material.getShuliang() // 订购数量 }; } // 初始化列选择器 private void initColumnSelector() { ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( requireContext(), R.array.table_headers, android.R.layout.simple_spinner_item ); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); columnSelector.setAdapter(adapter); // 添加"所有列"选项 columnSelector.setSelection(0); // 默认选择第一个选项(所有列) // 列选择变化监听 columnSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { applySearchFilter(); } @Override public void onNothingSelected(AdapterView<?> parent) {} }); } // 应用搜索过滤 private void applySearchFilter() { String query = searchView.getQuery().toString().trim().toLowerCase(); int selectedColumn = columnSelector.getSelectedItemPosition(); filteredTableRowsData.clear(); if (query.isEmpty()) { // 没有搜索词,显示所有数据 filteredTableRowsData.addAll(allTableRowsData); } else { // 根据选择的列进行过滤 for (Object[] row : allTableRowsData) { // 如果选择"所有列"(位置0),检查所有列 if (selectedColumn == 0) { for (Object cell : row) { if (cell != null && cell.toString().toLowerCase().contains(query)) { filteredTableRowsData.add(row); break; } } } // 检查特定列 else if (selectedColumn >= 1 && selectedColumn <= row.length) { int columnIndex = selectedColumn - 1; // 调整索引(0=所有列,1=第一列) if (row[columnIndex] != null && row[columnIndex].toString().toLowerCase().contains(query)) { filteredTableRowsData.add(row); } } } } // 刷新表格显示 refreshTableWithData(filteredTableRowsData); } /** * 刷新表格显示 */ private void refreshTableWithData(Iterable<? extends Object[]> dataToShow) { // 移除除表头外的所有行 int childCount = table.getChildCount(); if (childCount > 1) { table.removeViews(1, childCount - 1); } // 添加过滤后的行 for (Object[] rowData : dataToShow) { addTableRow(rowData); } } }每行添加 一个操作按扭
06-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值