Android学习1
1、Log日志
如果Logcat里的日志类型选的是Debug(Log.d),那么它和它前面的(Log.i,Log.w,Log.e)日志信息都会被显示,其他类型以此类推
2、注册点击事件的两种方式
Button testBtn = findViewById(R.id.testBtn); testBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } });
implements View.OnClickListener testBtn.setOnClickListener(this); @Override public void onClick(View view) { switch (view.getId()){ case R.id.testBtn: break;; } }
3、Dialog
public class TimeSelectDialog extends Dialog implements View.OnClickListener { public TimeSelectDialog(@NonNull Context context) { super(context); } public interface ClickCallback { void onClick(int year, int month, int day, int hour, int minute); } private ClickCallback ClickCallback_; public void SetCallBack(ClickCallback callback) { ClickCallback_ = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.time_select_dialog); SetDialogWidth(); Button okBtn = findViewById(R.id.selectTimeBtn2); okBtn.setOnClickListener(this); } public void UpdateTimer(int year, int month, int day, int hour, int minute) { DatePicker dp = findViewById(R.id.date_picker2); TimePicker tp = findViewById(R.id.time_picker2); dp.updateDate(year, month - 1, day); tp.setHour(hour); tp.setMinute(minute); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.selectTimeBtn2: if (ClickCallback_ != null) { DatePicker dp = findViewById(R.id.date_picker2); TimePicker tp = findViewById(R.id.time_picker2); ClickCallback_.onClick(dp.getYear(), dp.getMonth() + 1, dp.getDayOfMonth(), tp.getHour(), tp.getMinute()); } break; } } public void SetDialogWidth() { Window window = getWindow(); WindowManager.LayoutParams wlp = window.getAttributes(); Display display = window.getWindowManager().getDefaultDisplay(); Point point = new Point(); display.getSize(point); wlp.width = point.x; wlp.gravity = Gravity.BOTTOM; window.setBackgroundDrawableResource(android.R.color.background_dark); window.setAttributes(wlp); } } // 创建 TimeSelectDialog dialog = new TimeSelectDialog(PlaybackActivity.this); dialog.SetCallBack(new TimeSelectDialog.ClickCallback() { @Override public void onClick(int year, int month, int day, int hour, int minute) { endTimeTextView.setText(timeStop.dwYear + "-" + timeStop.dwMonth + "-" + timeStop.dwDay + " " + timeStop.dwHour + ":" + timeStop.dwMinute); dialog.hide(); } }); dialog.show(); dialog.UpdateTimer(timeStop.dwYear, timeStop.dwMonth, timeStop.dwDay, timeStop.dwHour, timeStop.dwMinute);
4、ViewPager
<androidx.viewpager.widget.ViewPager android:id="@+id/main_vp" android:layout_height="match_parent" android:layout_width="match_parent" android:layout_above="@id/main_bottom_layout"> </androidx.viewpager.widget.ViewPager>
public class CityWeatherFragment extends BaseFragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_city_weather, container, false);
// 通过view.findViewById()获取控件 // 获取从activity传过来的值 Bundle bundle = getArguments(); String provice_city = bundle.getString("city"); return view; }
private void initPager() { /* 创建Fragment对象,添加到ViewPager数据源当中*/ for (int i = 0; i < cityList.size(); i++) { CityWeatherFragment cwFrag = new CityWeatherFragment(); Bundle bundle = new Bundle(); bundle.putString("city",cityList.get(i)); cwFrag.setArguments(bundle); fragmentList.add(cwFrag); } }
package com.example.myapplication; import java.util.List; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; public class CityFragmentPagerAdapter extends FragmentStatePagerAdapter { List<Fragment>fragmentList; public CityFragmentPagerAdapter(FragmentManager fm, List<Fragment>fragmentLis) { super(fm); this.fragmentList = fragmentLis; } @Override public Fragment getItem(int position) { return fragmentList.get(position); } @Override public int getCount() { return fragmentList.size(); } int childCount = 0; //表示ViewPager包含的页数 // 当ViewPager的页数发生改变时,必须要重写两个函数 @Override public void notifyDataSetChanged() { this.childCount = getCount(); super.notifyDataSetChanged(); } @Override public int getItemPosition(@NonNull Object object) { if (childCount>0) { childCount--; return POSITION_NONE; } return super.getItemPosition(object); } }
mainVp = findViewById(R.id.main_vp); adapter = new CityFragmentPagerAdapter(getSupportFragmentManager(), fragmentList); mainVp.setAdapter(adapter); mainVp.setCurrentItem(0); mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { } @Override public void onPageScrollStateChanged(int state) { } });
FragmentStatePagerAdapter已淘汰,使用FragmentStateAdapter,并且viewpager使用viewpager2
public class ViewPageAdapter extends FragmentStateAdapter { List<Fragment> fragmentList; public ViewPageAdapter(@NonNull FragmentActivity fragmentActivity, List<Fragment> fragmentLis) { super(fragmentActivity); this.fragmentList = fragmentLis; } @NonNull @Override public Fragment createFragment(int position) { return fragmentList.get(position); } @Override public int getItemCount() { return fragmentList.size(); } }
5、系统对话框
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("雨伞指数"); builder.setMessage(msg); builder.setPositiveButton("确定",null); builder.create().show();
AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("提示信息").setMessage("确定要删除所有缓存么?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("取消",null); builder.create().show();
6、切换Activity并传参,获参
Intent intent = new Intent(MoreActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("city",city); startActivity(intent);
Intent intent = getIntent();
String city = intent.getStringExtra("city");
7、ListView
<ListView android:id="@+id/delete_lv" android:divider="@null" android:layout_width="match_parent" android:layout_height="match_parent"></ListView>
public class DeleteCityActivity extends AppCompatActivity implements View.OnClickListener{ ImageView errorIv,rightIv; ListView deleteLv; List<String>mDatas; //listview的数据源 List<String>deleteCitys; //表示存储了删除的城市信息 private DeleteCityAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_delete_city); errorIv = findViewById(R.id.delete_iv_error); rightIv = findViewById(R.id.delete_iv_right); deleteLv = findViewById(R.id.delete_lv); mDatas = DBManager.queryAllCityName(); deleteCitys = new ArrayList<>(); // 设置点击监听事件 errorIv.setOnClickListener(this); rightIv.setOnClickListener(this); // 适配器的设置 adapter = new DeleteCityAdapter(this, mDatas, deleteCitys); deleteLv.setAdapter(adapter); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.delete_iv_error: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("提示信息").setMessage("您确定要舍弃更改么?") .setPositiveButton("舍弃更改", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); //关闭当前的activity } }); builder.setNegativeButton("取消",null); builder.create().show(); break; case R.id.delete_iv_right: for (int i = 0; i < deleteCitys.size(); i++) { String city = deleteCitys.get(i); // 调用删除城市的函数 int i1 = DBManager.deleteInfoByCity(city); } // 删除成功返回上一级页面 finish(); break; } } }
public class DeleteCityAdapter extends BaseAdapter{ Context context; List<String>mDatas; List<String>deleteCitys; public DeleteCityAdapter(Context context, List<String> mDatas,List<String>deleteCitys) { this.context = context; this.mDatas = mDatas; this.deleteCitys = deleteCitys; } @Override public int getCount() { return mDatas.size(); } @Override public Object getItem(int position) { return mDatas.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { convertView = LayoutInflater.from(context).inflate(R.layout.item_deletecity,null); holder = new ViewHolder(convertView); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } final String city = mDatas.get(position); holder.tv.setText(city); holder.iv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDatas.remove(city); deleteCitys.add(city); notifyDataSetChanged(); //删除了提示适配器更新 } }); return convertView; } class ViewHolder{ TextView tv; ImageView iv; public ViewHolder(View itemView){ tv = itemView.findViewById(R.id.item_delete_tv); iv = itemView.findViewById(R.id.item_delete_iv); } } }
8、共享数据SharedPreferences
//存 SharedPreferences pref = getContext().getSharedPreferences("bg_pref", Context.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putInt("bg",0); editor.commit(); //取 SharedPreferences ref = getContext().getSharedPreferences("bg_pref", Context.MODE_PRIVATE); int bgNum = pref.getInt("bg", 2);
9、分享
Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT,s); startActivity(Intent.createChooser(intent,"分享"));
10、去除标题栏
在AndroidManifest.xml定位到android:theme对应的主题文件中去(记住是两个,一个是values文件夹下的,一个是values-night文件夹下的,都要改),把
parent="Theme.MaterialComponents.DayNight.DarkActionBar"
改为
parent="Theme.MaterialComponents.DayNight.NoActionBar"
11、Picasso:加载网络图片的框架
implementation 'com.squareup.picasso:picasso:2.5.2'
12、xutils:封装完善的多动能框架,此处主要使用网络获取数据功能
implementation 'org.xutils:xutils:3.7.6'
13、Gson:解析json数据的框架,简易方便
implementation 'com.google.code.gson:gson:2.2.4'
14、日历选择
Calendar cal = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { } },cal.get(Calendar.YEAR),cal.get(Calendar.MONTH),cal.get(Calendar.DAY_OF_MONTH)); DatePicker datePicker = datePickerDialog.getDatePicker(); datePicker.setMaxDate(new Date().getTime()); // 设置日期的上限日期 datePickerDialog.show();
15、