关于android:layout_weight=0.0dp android:layout_width=0.0dp android:layout_height=0.0dp 的问题

本文详细介绍如何使用LinearLayout及其layout_weight属性实现Android应用中的百分比布局,包括layout_weight的基础使用方法、weightSum属性的作用、剩余空间的概念及layout_width或layout_height属性的具体设置。

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

原文http://blog.youkuaiyun.com/wangdejun/article/details/42739983

在Android中对控件布局指定尺寸时,一般有两种方式:一种设定为自适应布局,即match_parent(fill_parent)或者wrap_content,通过根据父布局大小或者自己内容来产生一个动态尺寸;另外一种通过指定一个具体数值的方式定义成固定布局,单位可以是px/dp/sp等。这在绝大数情况下是可以解决问题的。

可是有没有办法像div+css里那样根据屏幕的尺寸,对控件布局进行“百分比”设定呢?这时就需要用到LinearLayout和他的子控件属性layout_weight。“layout_”前缀告诉我们此属性依赖于他的父布局。LinearLayout(线性布局)我们知道主要是让他的子控件实现并排或者并列的布局效果,一般子控件的大小是根据自身内容或者一个具体数值尺寸。而layout_weight(权重)属性则是表示当前控件在他的父布局的“剩余空间”中所占的比重(或者叫“比例”、“百分比”)。初看这段话可能不太好理解,我们看例子。


1.layout_weight值

我们希望下面两个按钮各占屏幕的一半:

竖屏效果横屏效果

那么只需要把两个按钮“layout_weight”值设成相等值(比如:1),并且把“layout_width”设成“0dp”,如下代码:

[html]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="horizontal">  
  5.   
  6.     <Button  
  7.         android:layout_width="0dp"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_weight="1"  
  10.         android:text="A"  
  11.         android:background="#fdb6b6"/>  
  12.   
  13.     <Button  
  14.         android:layout_width="0dp"  
  15.         android:layout_height="wrap_content"  
  16.         android:layout_weight="1"  
  17.         android:text="B"  
  18.         android:background="#b6d5fd"/>  
  19.   
  20. </LinearLayout>  

我们把LinearLayout的总空间(其实应该叫“剩余空间”,我们下面再说)看作100%,那么设定了“layout_weight”值的 总和 就代表100%。这里有两个控件设置了layout_weight(分别为1),所以值2就相当于100%空间。而按钮设定的值1就相当于 1 / 2 = 50%,代表当前控件占总空间的50%。因为LinearLayout的layout_width=“match_parent”,所以就相当于屏幕的50%。

既然如此,那么layout_weight具体是什么数值无所谓了,只要保证两个按钮的值相等就能实现各占50%了,我们把两个按钮的layout_weight同时设成“0.5”或者“2”看看,验证我们的推想。那么可不可以把layout_weight同时设成“0”?当然不行!layout_weight默认就是0,表示权重不起作用,控件依赖具体的layout_width或者layout_height起作用。

还有另一个问题,“layout_width”一定要设成“0dp”吗?一定要!,具体为什么,第四部分专门介绍。现在只要知道,如果我们平行百分比分割屏幕就要把“layout_width”设成“0dp”,而需要垂直百分比分割就把“layout_height”设成“0dp”。


2.weightSum值

如果我们只有一个按钮,希望占屏幕的50%并且在中间,如下面的效果:

竖屏效果横屏效果


我们只有一个控件可以设置layout_weight属性,而不管我们设多少,他都代表100%。这时父布局(LinearLayout)中的weightSum属性就可以大显身手了。weightSum的值就代表父布局的100%总空间,这是我们把LinearLayout的“weightSum”属性设置为“1”,按钮的“layout_weight”设置为“0.5”:

[html]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="horizontal"  
  5.     android:gravity="center"  
  6.     android:weightSum="1">  
  7.   
  8.     <Button  
  9.         android:layout_width="0dp"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_weight="0.5"  
  12.         android:text="A"  
  13.         android:background="#fdb6b6"/>  
  14.   
  15. </LinearLayout>  

其实weightSum一直存在,只是我们不设置时,默认为所有子控件“layout_weight”值的总和,就像第一部分介绍的样子。



3.剩余空间

前面我们提到layout_weight其实分割的是父空间的“剩余空间”,那么具体指的是哪部分空间呢?我们看个例子:


最右边的按钮的空间大小是根据其内容设置的,而左边的两个按钮则各占剩下空间的50%,这里的剩下空间就是我们一直说的“剩余空间”。在LinearLayout布局中首先把layout_weight=0(即没有设置layout_weight属性)的控件所占的空间去掉(这部分控件已经通过具体的layout_width和layout_height值指定了空间大小),再将剩下的空间交给设定了layout_weight值的控件按比百分比进行分割。而在前面两个例子中,因为全是设定了layout_weight的控件,所以“剩余空间”正好等于父布局的总空间了。本例的代码:

[html]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="horizontal">  
  5.   
  6.     <Button  
  7.         android:layout_width="0dp"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_weight="1"  
  10.         android:text="A"  
  11.         android:background="#fdb6b6"/>  
  12.   
  13.     <Button  
  14.         android:layout_width="0dp"  
  15.         android:layout_height="wrap_content"  
  16.         android:layout_weight="1"  
  17.         android:text="B"  
  18.         android:background="#b6d5fd"/>  
  19.   
  20.     <Button  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="CCCC"  
  24.         android:background="#b6fdc5"/>  
  25.   
  26. </LinearLayout>  


4.layout_width或layout_height的值

第一部分介绍到如果需要通过layout_weight来设置控件尺寸,一定要把layout_width或layout_height的值设定为“0dp”。那如果不这样做会怎样?我们先看第一个例子代码:

[html]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="horizontal">  
  5.   
  6.     <Button  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_weight="1"  
  10.         android:text="A"  
  11.         android:background="#fdb6b6"/>  
  12.   
  13.     <Button  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:layout_weight="1"  
  17.         android:text="B"  
  18.         android:background="#b6d5fd"/>  
  19.   
  20. </LinearLayout>  

将其中的layout_width设置成“wrap_content ”,看看运行效果:


如像设置了也没有影响啊,我们将右边的控件文字设长一点,再看看效果:


这时发现右边的控件被文字内容撑宽了,而不是我们希望的各50%,而如果将layout_width仍然改为“0dp”,则一切正常:



我们再看第二个例子,有三个按钮控件,其中A按钮占 50%,B和C按钮分别占25%,如下图:


如果我们把这三个按钮的layout_width属性都设成“math_parent”:

[html]  view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="horizontal">  
  5.   
  6.     <Button  
  7.         android:layout_width="match_parent"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_weight="2"  
  10.         android:text="A"  
  11.         android:background="#fdb6b6"/>  
  12.   
  13.     <Button  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:layout_weight="1"  
  17.         android:text="B"  
  18.         android:background="#b6d5fd"/>  
  19.   
  20.     <Button  
  21.         android:layout_width="match_parent"  
  22.         android:layout_height="wrap_content"  
  23.         android:layout_weight="1"  
  24.         android:text="C"  
  25.         android:background="#b6fdc5"/>  
  26.   
  27. </LinearLayout>  

会是什么效果呢?


这里layout_weight设置成2的A按钮反而没有了!什么原因,我们分析一下:

首先,布局需要计算“剩余空间”,因为ABC三个按钮控件都设置了math_parent的宽度,所以“剩余空间”变成了:

这里纠正一下第三部分“剩余空间”描述,不是去除layout_weight=0的控件,而是明确设置了宽高的值的控件的空间。

下面计算A按钮所占空间: 

B按钮所占空间 = 100%父空间           +         (-2 * 100%父空间)      *     25%    =      50%

C按钮和B按钮一样。所以如果我们给width或height设置了值,而layout_weight所产生的效果就不一定是我们想要的了。


<androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/listinfo" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/round_style" android:elevation="4dp" android:layout_margin="8dp" android:clickable="true" android:padding="10dp"> <com.xuexiang.xui.widget.textview.autofit.AutoFitTextView android:id="@+id/code" style="@style/item_show_title" android:layout_width="14dp" android:layout_height="16dp" android:paddingTop="2dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <com.xuexiang.xui.widget.textview.autofit.AutoFitTextView style="@style/item_show_title" android:id="@+id/name" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/code"/> <com.xuexiang.xui.widget.textview.autofit.AutoFitTextView style="@style/item_show_title" android:id="@+id/spec" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/name"/> <com.xuexiang.xui.widget.textview.autofit.AutoFitTextView style="@style/item_show_title" android:id="@+id/composition" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/spec"/> <com.xuexiang.xui.widget.textview.autofit.AutoFitTextView style="@style/item_show_title" android:id="@+id/weight" app:layout_constraintStart_toEndOf="@+id/composition" app:layout_constraintTop_toBottomOf="@+id/spec"/> <ImageView android:id="@+id/status" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/name" app:layout_constraintTop_toTopOf="parent" /> <View style="@style/item_show" android:id="@+id/view_task_list" android:layout_width="match_parent" android:layout_height="1dp" android:background="#cccccc" android:layout_marginTop="3dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/composition" app:layout_constraintStart_toStartOf="@+id/composition"/> </androidx.constraintlayout.widget.ConstraintLayout>点击表格,显示弹窗展示列内容
06-04
FanHui.java::package com.videogo.ui.login; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import com.videogo.openapi.EZOpenSDK; import ezviz.ezopensdk.R; import androidx.appcompat.app.AppCompatActivity; import java.util.Calendar; import java.util.Locale; import com.videogo.widget.TitleBar; import android.app.DatePickerDialog; public class FanHui extends AppCompatActivity { private static final String TAG = "EZPreview"; private String mAppKey; private String mDeviceSerial; private String mVerifyCode; private String mAccessToken; private int mCameraNo; private TextView mDateTextView; private int mSelectedYear, mSelectedMonth, mSelectedDay; private static final String KEY_APPKEY = "appkey"; private static final String KEY_SERIAL = "serial"; private static final String KEY_VERIFYCODE = "VerifyCode"; private static final String KEY_ACCESSTOKEN = "accessToken"; private static final String KEY_CAMERANO = "cameraNo"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ez_playback_list_page); extractParametersFromIntent(); final Calendar calendar = Calendar.getInstance(); mSelectedYear = calendar.get(Calendar.YEAR); mSelectedMonth = calendar.get(Calendar.MONTH); mSelectedDay = calendar.get(Calendar.DAY_OF_MONTH); // 设置日期显示模块 setupDatePicker(); View fanHui = findViewById(R.id.fanhui); fanHui.setOnClickListener(v -> finish()); Button huifangBtn = findViewById(R.id.fanhui); huifangBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 创建Intent跳转到FanHui活动 Intent intent = new Intent(FanHui.this, MainActivity.class); // 传递必要参数(可选) intent.putExtra("deviceSerial", mDeviceSerial); intent.putExtra("cameraNo", mCameraNo); intent.putExtra("accessToken", mAccessToken); intent.putExtra("appkey", mAppKey); intent.putExtra("verifyCode", mVerifyCode); startActivity(intent); } }); } private void setupDatePicker() { mDateTextView = findViewById(R.id.date_text); ImageButton datePickerButton = findViewById(R.id.date_picker_button); updateDateDisplay(); datePickerButton.setOnClickListener(v -> showDatePickerDialog()); } private void updateDateDisplay() { String formattedDate = String.format(Locale.getDefault(), "%d年%02d月%02d日", mSelectedYear, mSelectedMonth + 1, // 月份需要+1 mSelectedDay); mDateTextView.setText(formattedDate); } private void showDatePickerDialog() { DatePickerDialog datePickerDialog = new DatePickerDialog( this, (view, year, month, dayOfMonth) -> { // 更新日期 }, mSelectedYear, mSelectedMonth, mSelectedDay ); datePickerDialog.show(); } private void extractParametersFromIntent() { Bundle extras = getIntent().getExtras(); if (extras != null) { mAppKey = extras.getString(KEY_APPKEY, ""); mDeviceSerial = extras.getString(KEY_SERIAL, ""); mVerifyCode = extras.getString(KEY_VERIFYCODE, ""); mAccessToken = extras.getString(KEY_ACCESSTOKEN, ""); mCameraNo = extras.getInt(KEY_CAMERANO, 0); Log.d(TAG, "Received parameters:"); Log.d(TAG, "AppKey: " + mAppKey); Log.d(TAG, "DeviceSerial: " + mDeviceSerial); Log.d(TAG, "VerifyCode: " + mVerifyCode); Log.d(TAG, "AccessToken: " + mAccessToken); Log.d(TAG, "CameraNo: " + mCameraNo); } else { Log.e(TAG, "No parameters received from intent"); // 如果没有参数,可以显示错误信息并退出 // finish(); } } } FanHui代码的datepicker_layout.xml:<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/white" android:orientation="vertical" > <DatePicker android:id="@+id/dpPicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:calendarViewShown="false" /> <View android:layout_width="wrap_content" android:layout_height="1dp" android:layout_below="@id/dpPicker" android:background="#e1e5e7" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/dpPicker" android:layout_centerHorizontal="true" android:layout_marginTop="1dp" android:gravity="center" android:orientation="horizontal" > <RelativeLayout android:id="@+id/YES" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="确定" android:layout_margin="10dp" android:textColor="@android:color/black" android:textSize="22sp" /> </RelativeLayout> <View android:layout_width="1dp" android:layout_height="match_parent" android:background="#e1e5e7" /> <RelativeLayout android:id="@+id/NO" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="10dp" android:text="取消" android:textColor="@android:color/black" android:textSize="22sp" /> </RelativeLayout> </LinearLayout> </RelativeLayout> WeatherInfoActivity.java:package com.jd.projects.wlw.weatherinfo; import static com.jd.projects.wlw.weatherinfo.AllInfoMap.KEY_SITE_INFO; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.Display; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import com.jd.projects.wlw.DeviceMapActivity; import com.jd.projects.wlw.R; import com.jd.projects.wlw.bean.MapDataBean; import com.jd.projects.wlw.bean.new_webservice.MapDataBeanNew; import com.jd.projects.wlw.fragment.CureDataFragment; import com.jd.projects.wlw.fragment.HistoryDataFragment; import com.jd.projects.wlw.fragment.MonthDataFragment; import com.jd.projects.wlw.fragment.RealTimeFragment; import com.jd.projects.wlw.fragment.TjfxDataFragment; import com.jd.projects.wlw.update.Utils; import java.text.SimpleDateFormat; import java.util.Calendar; public class WeatherInfoActivity extends FragmentActivity implements OnClickListener { private LinearLayout layout_tqyb, layout_nyqx, layout_nyzx, layout_gdnq, layout_tjfx,layout_location; private ImageView image_ntqx, image_tqyb, image_nyzx, image_gdnq, image_tjfx; private Fragment mContent; public static MapDataBean realdata; // public static String asitename; private Calendar calendar = Calendar.getInstance(); private Context context; private ArrayAdapter<String> spinneradapter; private static final String[] m2 = {"空气温度", "空气湿度", "土壤温度1", "土壤温度2", "土壤温度3", "土壤湿度", "光照度", "蒸发量", "降雨量", "风速", "风向", "结露", "气压", "总辐射", "光合有效辐射"}; private static final String[] m1 = {"空气温度", "空气湿度", "土壤温度1", "土壤温度2", "土壤温度3", "土壤湿度1", "土壤湿度2", "土壤湿度3"}; private String spinnervaluse02; TextView time1; private String nsitetype; private MapDataBeanNew curSiteInfo; private double intentLat = 0.0; private double intentLng = 0.0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_wheatherinfo); try { intentLat = getIntent().getDoubleExtra("intentLat", 0.0); intentLng = getIntent().getDoubleExtra("intentLng", 0.0); context = this; //getData(); curSiteInfo = (MapDataBeanNew) getIntent().getSerializableExtra(KEY_SITE_INFO); initView(); if(intentLat == 0 || intentLng == 0){ layout_location.setVisibility(View.GONE); }else{ layout_location.setVisibility(View.VISIBLE); } } catch (Exception e){ Log.d("mcg",e.getMessage()); e.printStackTrace(); } } private void getData() { SharedPreferences preferences = getSharedPreferences("wlw_settings", MODE_PRIVATE); String neiip = preferences.getString("neiip", ""); String mark = preferences.getString("netmode", "");//内网访问还是外网访问? nsitetype = AllInfoMap.nsitetype;// } private void initView() { nsitetype = AllInfoMap.nsitetype;// layout_tqyb = (LinearLayout) findViewById(R.id.tab1); layout_nyqx = (LinearLayout) findViewById(R.id.tab2); layout_nyzx = (LinearLayout) findViewById(R.id.tab3); layout_gdnq = (LinearLayout) findViewById(R.id.tab4); layout_tjfx = (LinearLayout) findViewById(R.id.tab5); layout_location = (LinearLayout) findViewById(R.id.tab6); image_ntqx = (ImageView) findViewById(R.id.image_qixiang);//2 image_tqyb = (ImageView) findViewById(R.id.image_yubao);//1 image_nyzx = (ImageView) findViewById(R.id.image_zixun);//3 image_gdnq = (ImageView) findViewById(R.id.image_gdnq);//4 image_tjfx = (ImageView) findViewById(R.id.image_tjfx);//5 layout_tqyb.setOnClickListener(this); layout_nyqx.setOnClickListener(this); layout_nyzx.setOnClickListener(this); layout_gdnq.setOnClickListener(this); layout_tjfx.setOnClickListener(this); layout_location.setOnClickListener(this); mContent = RealTimeFragment.newInstance(curSiteInfo); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit(); } @SuppressLint("NonConstantResourceId") @Override public void onClick(View v) { switch (v.getId()) { case R.id.tab1: layout_tqyb.setBackgroundResource(R.drawable.tabshape_bg); layout_nyqx.setBackgroundResource(R.color.transparent); layout_nyzx.setBackgroundResource(R.color.transparent); layout_gdnq.setBackgroundResource(R.color.transparent); layout_tjfx.setBackgroundResource(R.color.transparent); image_tjfx.setImageResource(R.drawable.sh_wxry_rwcx_02); image_nyzx.setImageResource(R.drawable.curve); image_ntqx.setImageResource(R.drawable.history_pic); image_gdnq.setImageResource(R.drawable.disease_pic); image_tqyb.setImageResource(R.drawable.real_pic_on); mContent = RealTimeFragment.newInstance(curSiteInfo); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit(); break; case R.id.tab2: layout_tqyb.setBackgroundResource(R.color.transparent); layout_nyqx.setBackgroundResource(R.drawable.tabshape_bg); layout_nyzx.setBackgroundResource(R.color.transparent); layout_gdnq.setBackgroundResource(R.color.transparent); layout_tjfx.setBackgroundResource(R.color.transparent); image_tjfx.setImageResource(R.drawable.sh_wxry_rwcx_02); image_gdnq.setImageResource(R.drawable.disease_pic); image_tqyb.setImageResource(R.drawable.real_pic); image_ntqx.setImageResource(R.drawable.history_pic_on); image_nyzx.setImageResource(R.drawable.curve); mContent = HistoryDataFragment.newInstance(curSiteInfo); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit(); break; case R.id.tab3: showExitGameAlert(); break; case R.id.tab4: layout_tqyb.setBackgroundResource(R.color.transparent); layout_nyqx.setBackgroundResource(R.color.transparent); layout_nyzx.setBackgroundResource(R.color.transparent); layout_gdnq.setBackgroundResource(R.drawable.tabshape_bg); layout_tjfx.setBackgroundResource(R.color.transparent); image_tjfx.setImageResource(R.drawable.sh_wxry_rwcx_02); image_gdnq.setImageResource(R.drawable.disease_pic_on); image_tqyb.setImageResource(R.drawable.real_pic); image_ntqx.setImageResource(R.drawable.history_pic); image_nyzx.setImageResource(R.drawable.curve); mContent = CureDataFragment.newInstance(curSiteInfo); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit(); break; case R.id.tab5: jinDuJiaozhang(); break; case R.id.tab6: Intent intent = new Intent(WeatherInfoActivity.this, DeviceMapActivity.class); intent.putExtra("intentLat",intentLat); intent.putExtra("intentLng",intentLng); startActivity(intent); break; case R.id.dateselect1: //弹窗日期选择 new MonPickerDialog(context, dateListener1, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show(); break; } } private DatePickerDialog.OnDateSetListener dateListener1 = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) { calendar.set(Calendar.YEAR, arg1);// 将给定的日历字段设置为给定值。 //calendar.set(Calendar.MONTH, arg2); //calendar.set(Calendar.DAY_OF_MONTH, arg3); SimpleDateFormat df = new SimpleDateFormat("yyyy"); time1.setText(df.format(calendar.getTime())); } }; /** * 时间选择器 */ @SuppressLint("SimpleDateFormat") private void showExitGameAlert() { final AlertDialog dlg = new AlertDialog.Builder(this).create(); dlg.show(); Window window = dlg.getWindow(); // *** 主要就是在这里实现这种效果的. // 设置窗口的内容页面,shrew_exit_dialog.xml文件中定义view内容 window.setContentView(R.layout.datepicker_layout); // 为确认按钮添加事件,执行退出应用操作 DatePicker dp = (DatePicker) window.findViewById(R.id.dpPicker); final Calendar calendar = Calendar.getInstance(); // final SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月"); final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM"); // 隐藏日期View ((ViewGroup) ((ViewGroup) dp.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE); dp.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), (view, year, monthOfYear, dayOfMonth) -> { // 获取一个日历对象,并初始化为当前选中的时间 calendar.set(year, monthOfYear, dayOfMonth); }); RelativeLayout ok = (RelativeLayout) window.findViewById(R.id.YES); ok.setOnClickListener(v -> { layout_tqyb.setBackgroundResource(R.color.transparent); layout_nyqx.setBackgroundResource(R.color.transparent); layout_nyzx.setBackgroundResource(R.drawable.tabshape_bg); layout_gdnq.setBackgroundResource(R.color.transparent); layout_tjfx.setBackgroundResource(R.color.transparent); image_tjfx.setImageResource(R.drawable.sh_wxry_rwcx_02); image_gdnq.setImageResource(R.drawable.disease_pic); image_tqyb.setImageResource(R.drawable.real_pic); image_ntqx.setImageResource(R.drawable.history_pic); image_nyzx.setImageResource(R.drawable.curve_hover); String dataTime = format.format(calendar.getTime()); // 携带数据跳转页面 mContent = new MonthDataFragment(); Bundle bundle = new Bundle(); bundle.putString("datatime", dataTime); bundle.putSerializable(KEY_SITE_INFO, curSiteInfo); mContent.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit(); dlg.cancel(); }); // 关闭alert对话框架 RelativeLayout cancel = (RelativeLayout) window.findViewById(R.id.NO); cancel.setOnClickListener(v -> dlg.cancel()); } /** * 重写datePicker 1.只显示 年-月 2.title 只显示 年-月 * * @author lmw */ public class MonPickerDialog extends DatePickerDialog { public MonPickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) { super(context, callBack, year, monthOfYear, dayOfMonth); //this.setTitle(year + "年" + (monthOfYear + 1) + "月"); this.setTitle(year + "年"); ((ViewGroup) ((ViewGroup) this.getDatePicker().getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE); ((ViewGroup) ((ViewGroup) this.getDatePicker().getChildAt(0)).getChildAt(0)).getChildAt(1).setVisibility(View.GONE); } @Override public void onDateChanged(DatePicker view, int year, int month, int day) { super.onDateChanged(view, year, month, day); //this.setTitle(year + "年" + (month + 1) + "月"); this.setTitle(year + "年"); } } private void jinDuJiaozhang() { final Dialog myDialog = new Dialog(context); //dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0)); myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); myDialog.show(); // 设置宽度为屏幕的宽度 WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); WindowManager.LayoutParams lp = myDialog.getWindow().getAttributes(); lp.width = (int) (display.getWidth()); // 设置宽度 myDialog.getWindow().setAttributes(lp); //myDialog.setCancelable(false);//调用这个方法时,按对话框以外的地方不起作用。按返回键也不起作用 myDialog.setCanceledOnTouchOutside(false);//调用这个方法时,按对话框以外的地方不起作用。按返回键还起作用 Window window = myDialog.getWindow(); window.setContentView(R.layout.dialog_et22);// setContentView()必须放在show()的后面,不然会报错 Spinner sp_01 = (Spinner) window.findViewById(R.id.sp_01); // 将可选内容与ArrayAdapter连接起来 if (nsitetype.equals("01") || !Utils.isOldDevice(curSiteInfo.getId())) { // 十五项因子 spinneradapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, m2); } else if (nsitetype.equals("02")) { // 八项因子 spinneradapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, m1); } // 设置下拉列表的风格 spinneradapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // 将adapter 添加到spinner中 sp_01.setAdapter(spinneradapter); sp_01.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub /*if (position == 0) { spinnervaluse02 = "卵"; } else if (position == 1) { spinnervaluse02 = "幼虫"; } else if (position == 2) { spinnervaluse02 = "蛹"; } else if (position == 3) { spinnervaluse02 = "成虫"; }*/ if (nsitetype.equals("01") || !Utils.isOldDevice(curSiteInfo.getId())) { // 十五项因子 spinnervaluse02 = m2[position]; } else if (nsitetype.equals("02")) { // 八项因子 spinnervaluse02 = m1[position]; } } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); time1 = (TextView) window.findViewById(R.id.time1); LinearLayout dateselect1 = (LinearLayout) window.findViewById(R.id.dateselect1); // 初始化当前时间 updateDate(); dateselect1.setOnClickListener(this); Button btn_ensure = (Button) window.findViewById(R.id.btn_ensure); Button btn_cancel = (Button) window.findViewById(R.id.btn_cancel); btn_ensure.setOnClickListener(v -> { //spinnervaluse02 time1 //统计分析 layout_tqyb.setBackgroundResource(R.color.transparent); layout_nyqx.setBackgroundResource(R.color.transparent); layout_nyzx.setBackgroundResource(R.color.transparent); layout_gdnq.setBackgroundResource(R.color.transparent); layout_tjfx.setBackgroundResource(R.drawable.tabshape_bg); image_tjfx.setImageResource(R.drawable.sh_wxry_rwcx_01); image_gdnq.setImageResource(R.drawable.disease_pic); image_tqyb.setImageResource(R.drawable.real_pic); image_ntqx.setImageResource(R.drawable.history_pic); image_nyzx.setImageResource(R.drawable.curve); mContent =new TjfxDataFragment(); Bundle bundle = new Bundle(); bundle.putString("spinnervaluse", spinnervaluse02); bundle.putString("time1", time1.getText().toString()); bundle.putSerializable(KEY_SITE_INFO,curSiteInfo); mContent.setArguments(bundle); getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit(); myDialog.dismiss(); }); btn_cancel.setOnClickListener(v -> { // TODO Auto-generated method stub myDialog.dismiss(); }); } private void updateDate() {//时间控件 SimpleDateFormat df = new SimpleDateFormat("yyyy"); time1.setText(df.format(calendar.getTime())); } } WeatherInfoActivity代码的datepicker_layout.xml:<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/white" android:orientation="vertical" > <DatePicker android:id="@+id/dpPicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:calendarViewShown="false" /> <View android:layout_width="wrap_content" android:layout_height="1dp" android:layout_below="@id/dpPicker" android:background="#e1e5e7" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/dpPicker" android:layout_centerHorizontal="true" android:layout_marginTop="1dp" android:gravity="center" android:orientation="horizontal" > <RelativeLayout android:id="@+id/YES" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="确定" android:layout_margin="10dp" android:textColor="@android:color/black" android:textSize="22sp" /> </RelativeLayout> <View android:layout_width="1dp" android:layout_height="match_parent" android:background="#e1e5e7" /> <RelativeLayout android:id="@+id/NO" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:layout_margin="10dp" android:text="取消" android:textColor="@android:color/black" android:textSize="22sp" /> </RelativeLayout> </LinearLayout> </RelativeLayout> 依据上述代码解释为什么datepicker_layout.xml代码一样,但是在WeatherInfoActivity和FanHui使用中显示布局不一样。
06-26
在我给的代码基础上改只要改运算符显示这一块:package com.example.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ArrayAdapter import android.widget.Spinner import android.widget.TextView import android.widget.Toast import com.google.android.material.button.MaterialButton import com.google.android.material.textfield.TextInputEditText class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 初始化UI组件 val num1Input = findViewById<TextInputEditText>(R.id.editTextNumber1) val num2Input = findViewById<TextInputEditText>(R.id.editTextNumber2) val operatorSpinner = findViewById<Spinner>(R.id.spinnerOperator) val calculateBtn = findViewById<MaterialButton>(R.id.buttonCalculate) val resultText = findViewById<TextView>(R.id.textViewResult) // 配置Spinner适配器 val operators = resources.getStringArray(R.array.operators) val adapter = ArrayAdapter( this, android.R.layout.simple_spinner_item, operators ).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } operatorSpinner.adapter = adapter operatorSpinner.setSelection(0) // 默认选中第一个运算符 calculateBtn.setOnClickListener { // 获取输入值 val num1Str = num1Input.text.toString() val num2Str = num2Input.text.toString() val operator = operatorSpinner.selectedItem.toString() // 验证输入 if (num1Str.isEmpty() || num2Str.isEmpty()) { Toast.makeText(this, R.string.error_empty, Toast.LENGTH_SHORT).show() return@setOnClickListener } val num1 = num1Str.toDoubleOrNull() val num2 = num2Str.toDoubleOrNull() if (num1 == null || num2 == null) { Toast.makeText(this, R.string.error_invalid, Toast.LENGTH_SHORT).show() return@setOnClickListener } // 执行计算 val result = when (operator) { "+" -> num1 + num2 "-" -> num1 - num2 "*" -> num1 * num2 "/" -> { if (num2 == 0.0) { Toast.makeText(this, R.string.error_divide_zero, Toast.LENGTH_SHORT).show() return@setOnClickListener } num1 / num2 } else -> 0.0 } // 显示结果(保留两位小数) resultText.text = "%.2f".format(result) } } } <!-- 运算符选择下拉菜单 --> <com.google.android.material.textfield.TextInputLayout android:id="@+id/textInputLayoutOperator" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" app:boxBackgroundMode="outline" app:boxCornerRadiusTopStart="12dp" app:boxCornerRadiusTopEnd="12dp" app:boxStrokeColor="@color/purple_200" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@id/textInputLayout2"> <com.google.android.material.textfield.MaterialAutoCompleteTextView android:id="@+id/spinnerOperator" android:layout_width="match_parent" android:layout_height="wrap_content" android:entries="@string/result_hint" android:inputType="none" android:padding="8dp" android:textSize="16sp" /> </com.google.android.material.textfield.TextInputLayout>
07-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值