萌新学习安卓开发记录
先上效果图:
我是想要一个类似DatePicker
控件中spinner模式的日期选择器,然后赋值给我的文本。
但是由于实力不允许,看了好长时间没有学会基于DatePicker
的自定义控件。
于是在对AI各种强势逼问下终于找到了类似的控件——NumberPicker。
又是一番操作后,得到了一个可以直接引用的NumberDialog类:
package com.example.yourapp;//此处改为自己的应用名
import android.content.Context;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import java.util.Calendar;
public class NumberDialog {
private Context context;
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
LinearLayout linearLayout;
public NumberDialog(Context context, TextView textView) {// 回传TextView
this.context = context;
linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setGravity(Gravity.CENTER);
// 初始化NumberPicker
NumberPicker yearPicker = new NumberPicker(context);
yearPicker.setMinValue(2000);//设置最小年份
yearPicker.setMaxValue(2100);//设置最大年份
yearPicker.setValue(year); //设置默认值为当前年份
// 设置年份NumberPicker的字体大小
float textSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 30, context.getResources().getDisplayMetrics());//赋值默认字体大小
yearPicker.setTextSize(textSize);
// 创建月份NumberPicker
NumberPicker monthPicker = new NumberPicker(context);
monthPicker.setMinValue(1);//设置最小月份
monthPicker.setMaxValue(12);//设置最大月份
monthPicker.setValue(month + 1);//设置默认值为当前月份(月份从0开始,所以加1)
monthPicker.setTextSize(textSize);//设置月份NumberPicker的字体大小
// 设置布局参数
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
0, // 宽度为0,表示根据权重分配
LinearLayout.LayoutParams.WRAP_CONTENT // 高度根据内容自动调整
);
layoutParams.weight = 1; // 权重为1,表示平分宽度
// 将两个NumberPicker添加到LinearLayout中
linearLayout.addView(yearPicker, layoutParams);
linearLayout.addView(monthPicker, layoutParams);
//创建并显示日期选择对话框
new AlertDialog.Builder(context)
.setTitle("选择年份和月份")
.setView(linearLayout)
.setPositiveButton("确定", (dialog, which) -> {
// 获取选择的年份和月份
int selectedYear = yearPicker.getValue();
int selectedMonth = monthPicker.getValue() - 1;
// 在这里处理选择的年份和月份,例如显示在TextView中
String selectedDate = String.format("%04d年%02d月", selectedYear, selectedMonth + 1);
textView.setText(selectedDate);
})
.setNegativeButton("取消", null)
.show();
}
}
在Activity中引用为:
public class MainActivity extends AppCompatActivity {
private TextView textView,textView1;//作者此处textView有他用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1=findViewById(R.id.textView1);
textView1.setOnClickListener(v -> {
new NumberDialog(MainActivity.this,textView1);//把弹窗回传的数据传到textView1
});
}
}
萌新创作,以上代码均来自AI。