我需要在小部件渲染后调用该方法,否则会出错。所以我想知道是否有任何方法可以检查小部件的状态,也许听众可以提供帮助?
CyberDemon's questions
我想通过索引获取键和值,但我不知道如何实现,我查看了其他语言的解决方案,我什么都不懂,如果您能提供帮助,我将不胜感激?
我有一个类DBHelper
,我可以使用它在数据库中添加和删除数据。我遇到了这种问题,我无法获得列数。我在 Stack 上看到了同样的问题,但我不知道如何创建一个可以获取列数的类方法。他在那里以某种方式初始化了数据库,我无法理解。如果您能提供帮助,我将不胜感激)
这是那个代码
int count = Sqflite.firstIntValue(await db.rawQuery('SELECT COUNT(*) FROM table_name'));
DBHelper 代码
import 'dart:async';
import 'dart:io' as io;
import 'package:janzer/database_model.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
class DBHelper {
static Database db_instance;
final String TABLE_NAME = "DatabaseModel";
Future<Database> get db async {
if (db_instance == null) db_instance = await initDB();
return db_instance;
}
initDB() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "maps_database.db");
var db = await openDatabase(path, version: 3, onCreate: onCreateFunc);
return db;
}
void onCreateFunc(Database db, int version) async {
await db.execute('CREATE TABLE $TABLE_NAME'
'(id INTEGER PRIMARY KEY,'
'realTime TEXT, '
'moduleDate TEXT, '
'moduleTime TEXT, '
'moduleDay TEXT, '
'gpsCoordinates TEXT, '
'gpsSatellites TEXT, '
'gpsTime TEXT, '
'gpsDate TEXT, '
'temperature TEXT, '
'pressure TEXT, '
'humidity TEXT, '
'dust TEXT, '
'zivert TEXT )');
}
//getData
Future<List<DatabaseModel>> getContacts() async {
var db_connection = await db;
List<Map> list = await db_connection.rawQuery('SELECT * FROM $TABLE_NAME');
List<DatabaseModel> databaseModelS = new List();
for (int i = 0; i < list.length; i++) {
DatabaseModel databaseModel = new DatabaseModel();
databaseModel.id = list[i]['id'];
databaseModel.realTime = list[i]['realTime'];
databaseModel.moduleDate = list[i]['moduleDate'];
databaseModel.moduleTime = list[i]['moduleTime'];
databaseModel.moduleDay = list[i]['moduleDay'];
databaseModel.gpsCoordinates = list[i]['systemTime'];
databaseModel.gpsSatellites = list[i]['gpsSatellites'];
databaseModel.gpsTime = list[i]['gpsTime'];
databaseModel.gpsDate = list[i]['gpsDate'];
databaseModel.temperature = list[i]['temperature'];
databaseModel.pressure = list[i]['pressure'];
databaseModel.humidity = list[i]['humidity'];
databaseModel.dust = list[i]['dust'];
databaseModel.sievert = list[i]['zivert'];
databaseModelS.add(databaseModel);
}
return databaseModelS;
}
void addNewContact(DatabaseModel databaseModel) async {
var db_connection = await db;
String query = 'INSERT INTO '
'$TABLE_NAME(realTime, '
'moduleDate, '
'moduleTime, '
'moduleDay, '
'gpsCoordinates, '
'gpsSatellites, '
'gpsTime, '
'gpsDate, '
'temperature, '
'temperature, '
'pressure, '
'dust, '
'zivert) '
'VALUES( \'${databaseModel.realTime}\','
'\'${databaseModel.moduleDate}\', '
'\'${databaseModel.moduleTime}\','
'\'${databaseModel.moduleDay}\','
'\'${databaseModel.gpsCoordinates}\', '
'\'${databaseModel.gpsSatellites}\','
'\'${databaseModel.gpsTime}\','
'\'${databaseModel.gpsDate}\','
'\'${databaseModel.temperature}\', '
'\'${databaseModel.pressure}\', '
'\'${databaseModel.humidity}\','
'\'${databaseModel.dust}\','
'\'${databaseModel.sievert}\')';
await db_connection.transaction((transition) async {
return await transition.rawInsert(query);
});
}
void updateContact(DatabaseModel databaseModel) async {
var db_connection = await db;
String query =
'UPDATE $TABLE_NAME SET name ='
'\'${databaseModel.realTime}\','
'\'${databaseModel.moduleDate}\', '
'\'${databaseModel.moduleTime}\','
'\'${databaseModel.moduleDay}\','
'\'${databaseModel.gpsCoordinates}\', '
'\'${databaseModel.gpsSatellites}\','
'\'${databaseModel.gpsTime}\','
'\'${databaseModel.gpsDate}\','
'\'${databaseModel.temperature}\', '
'\'${databaseModel.pressure}\', '
'\'${databaseModel.humidity}\','
'\'${databaseModel.dust}\','
'\'${databaseModel.sievert}\' WHERE id = ${databaseModel.id}';
await db_connection.transaction((transition) async {
return await transition.rawQuery(query);
});
}
void deleteContact(DatabaseModel databaseModel) async {
var db_connection = await db;
String query = 'DELETE FROM $TABLE_NAME WHERE id = ${databaseModel.id}';
await db_connection.transaction((transition) async {
return await transition.rawQuery(query);
});
}
}
型号类代码
class DatabaseModel {
DatabaseModel();
String realTime,
moduleDate,
moduleTime,
moduleDay,
gpsCoordinates,
gpsSatellites,
gpsTime,
gpsDate,
temperature,
pressure,
humidity,
dust,
countDB,
sievert;
int id;
}
亲爱的开发者。几天来我无法理解如何正确使用:Futures、Streams 和 Async / Await。我在官方频道看了视频,但最后我什么也看不懂。如果有人可以向我解释这将是很酷的。因为我经常使用这些类和函数提出问题,但我不明白它们是如何工作的。感谢您的理解))
我有一个模态底部表,它有两个单选按钮。但是当按下时,它们不起作用。我不知道问题是什么,我认为这是因为单选按钮位于底部表中。
这是我的代码
import 'package:flutter/material.dart';
class NutritionScreen extends StatefulWidget {
@override
_NutritionScreenState createState() => _NutritionScreenState();
}
class _NutritionScreenState extends State<NutritionScreen> {
double height = 500.0;
TextEditingController textFieldControllerAge = TextEditingController();
TextEditingController textFieldControllerGrowth = TextEditingController();
TextEditingController textFieldControllerWeight = TextEditingController();
TextEditingController textFieldControllerWeightGoal = TextEditingController();
bool _validateAge = false;
bool _validateGrowth = false;
bool _validateWeight = false;
bool _validateWeightGoal = false;
// Declare this variable
int selectedRadioTile;
@override
void initState() {
super.initState();
selectedRadioTile = 0;
}
setSelectedRadioTile(int val) {
setState(() {
selectedRadioTile = val;
});
}
@override
void dispose() {
textFieldControllerAge.dispose();
textFieldControllerGrowth.dispose();
textFieldControllerWeight.dispose();
textFieldControllerWeightGoal.dispose();
super.dispose();
}
void _modalBottomSheetMenu() {
showModalBottomSheet(
context: context,
builder: (builder) {
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery
.of(context)
.viewInsets
.bottom),
child: new Container(
height: height,
color: Colors
.transparent, //could change this to Color(0xFF737373),
//so you don't have to change MaterialApp canvasColor
child: new Container(
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(10.0),
topRight: const Radius.circular(10.0))),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: EdgeInsets.all(8.0),
child: Text(
"Питание",
textAlign: TextAlign.center,
style:
TextStyle(color: Colors.black, fontSize: 26.0),
)),
Padding(padding: EdgeInsets.all(8.0),
child: TextField(
maxLines: 1,
textDirection: TextDirection.ltr,
controller: textFieldControllerAge,
style: TextStyle(
color: Colors.lightGreen[400],
fontSize: 18.5),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 4.0),
labelText: "Возраст",
errorText: _validateAge ? 'Поле должно быть заполненным' : null,
alignLabelWithHint: false,
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.done,
)),
Padding(padding: EdgeInsets.all(8.0),
child: TextField(
maxLines: 1,
textDirection: TextDirection.ltr,
controller: textFieldControllerGrowth,
style: TextStyle(
color: Colors.lightGreen[400],
fontSize: 18.5),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 4.0),
labelText: "Рост",
errorText: _validateGrowth ? 'Поле должно быть заполненным' : null,
alignLabelWithHint: false,
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.done,
)),
Padding(padding: EdgeInsets.all(8.0),
child: TextField(
maxLines: 1,
textDirection: TextDirection.ltr,
controller: textFieldControllerWeight,
style: TextStyle(
color: Colors.lightGreen[400],
fontSize: 18.5),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 4.0),
labelText: "Вес",
errorText: _validateWeight ? 'Поле должно быть заполненным' : null,
alignLabelWithHint: false,
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.done,
)),
Padding(padding: EdgeInsets.all(8.0),
child: TextField(
maxLines: 1,
textDirection: TextDirection.ltr,
controller: textFieldControllerWeightGoal,
style: TextStyle(
color: Colors.lightGreen[400],
fontSize: 18.5),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 4.0),
labelText: "Целевой вес",
errorText: _validateWeightGoal ? 'Поле должно быть заполненным' : null,
alignLabelWithHint: false,
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.done,
)),
RadioListTile(
value: 0,
groupValue: selectedRadioTile,
title: Text("Мужчина"),
onChanged: (val) {
setSelectedRadioTile(val);
},
activeColor: Colors.lightGreen[400],
selected: true,
),
RadioListTile(
value: 1,
groupValue: selectedRadioTile,
title: Text("Женщина"),
onChanged: (val) {
setSelectedRadioTile(val);
},
activeColor: Colors.lightGreen[400],
selected: false,
),
Container(
alignment: Alignment.bottomRight,
margin: EdgeInsets.only(top: 30),
child: Padding(
padding: EdgeInsets.all(16.0),
child: FloatingActionButton(
heroTag: "tag4",
backgroundColor: Color(0xffFF7070),
child: Icon(
Icons.check, color: Colors.white),
onPressed: () {
setState(() {
textFieldControllerAge.text.isEmpty ?
_validateAge = true : _validateAge = false;
textFieldControllerGrowth.text.isEmpty ?
_validateGrowth = true : _validateGrowth = false;
textFieldControllerWeight.text.isEmpty ?
_validateWeight = true : _validateWeight = false;
textFieldControllerWeightGoal.text.isEmpty ?
_validateWeightGoal = true : _validateWeightGoal = false;
});
if(textFieldControllerAge.text.isNotEmpty &&
textFieldControllerGrowth.text.isNotEmpty &&
textFieldControllerWeight.text.isNotEmpty &&
textFieldControllerWeightGoal.text.isNotEmpty)
_sendDataToSecondScreen(context);
}))),
],
)),
)),
);
});
}
void _sendDataToSecondScreen(BuildContext context) {
String textAge = textFieldControllerAge.text;
String textGrowth = textFieldControllerGrowth.text;
String textWeight = textFieldControllerWeight.text;
String textWeightGoal = textFieldControllerWeightGoal.text;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
MainNutrition(
textAge: textAge,
textGrowth: textGrowth,
textWeight: textWeight,
textWeightGoal: textWeightGoal),
// Этого класса нет
));
}
@override
Widget build(BuildContext context) {
return new Scaffold(
resizeToAvoidBottomInset: false,
backgroundColor: Color(0xff2b2b2b),
appBar: AppBar(
backgroundColor: Colors.lightGreen[400],
title: Text(
'Питание',
style: new TextStyle(color: Colors.white),
),
leading: IconButton(
icon: Icon(Icons.arrow_back),
color: Colors.white,
onPressed: () => Navigator.of(context).pop(),
),
),
body: Container(
alignment: Alignment.center,
margin: const EdgeInsets.only(bottom: 45.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 200.0),
child: Text(
"Нажми на кнопку, чтобы добавить правильный рацион питания.",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 20.0),
)),
FloatingActionButton(
heroTag: "tag3",
backgroundColor: Color(0xffFF7070),
child: Icon(Icons.add, color: Colors.white),
onPressed: () {
_modalBottomSheetMenu();
}),
],
),
),
);
}
}
如何将数据从 alertdialog 传递到同一个 Flutter 页面?
class MeasurementsScreen extends StatefulWidget {
@override
_MeasurementsScreenState createState() => _MeasurementsScreenState();
}
class _MeasurementsScreenState extends State<MeasurementsScreen> {
List<_ListItem> listItems;
String lastSelectedValue;
var name = ["Рост", "Вес"];
var indication = ["Введите ваш рост", "Введите ваш вес"];
TextEditingController customcintroller;
void navigationPageProgrammTrainingHandler() {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => ProgrammTrainingHandler()),
);
}
@override
void initState() {
super.initState();
initListItems();
}
Future<String> createAlertDialog(BuildContext context, int indexAl){
customcintroller = TextEditingController();
if(indexAl < 2){
return showDialog(context: context, builder: (context){
return AlertDialog(
title: Text(name[indexAl]),
content: TextField(
textDirection: TextDirection.ltr,
controller: customcintroller,
style: TextStyle(
color: Colors.lightGreen[400],
fontSize: 18.5),
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 4.0),
labelText: indication[indexAl],
alignLabelWithHint: false,
),
keyboardType: TextInputType.phone,
textInputAction: TextInputAction.done,
),
actions: <Widget>[
FlatButton(
child: const Text('ОТМЕНА'),
onPressed: () {
Navigator.of(context).pop();
},
),
FlatButton(
child: const Text('ОК'),
onPressed: () {
Navigator.of(context).pop(customcintroller.text.toString());
},
),
],
);
});
} else if (indexAl > 1){
navigationPageProgrammTrainingHandler();
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Color(0xff2b2b2b),
appBar: AppBar(
title: Text(
'Замеры',
style: new TextStyle(
color: Colors.white,
),),
leading: IconButton(
icon:Icon(Icons.arrow_back),
color: Colors.white ,
onPressed:() => Navigator.of(context).pop(),
),
),
body: ListView.builder(
physics: BouncingScrollPhysics(),
itemCount: listItems.length,
itemBuilder: (BuildContext ctxt, int index){
return GestureDetector(
child: listItems[index],
onTap: () {
createAlertDialog(context, index).then((onValue){
});
}
);
},
),
);
}
void initListItems() {
listItems = [
new _ListItem(
bgName: 'assets/images/soso_growth.jpg',
name: customcintroller.text.toString().isEmpty == false ? customcintroller.text.toString() : "Рост",
detail: "Нажми, чтобы добавить свой рост"),
new _ListItem(
bgName: 'assets/images/soso_weight.jpg',
name: customcintroller.text.toString().isEmpty == false ? customcintroller.text.toString() : "Вес",
detail: "Нажми, чтобы добавить свой вес"),
new _ListItem(
bgName: 'assets/images/soso_chest.jpg',
name: "Грудь",
detail: "PRO-версия"),
new _ListItem(
bgName: 'assets/images/soso_shoulder.jpg',
name: "Плечи",
detail: "PRO-версия"),
new _ListItem(
bgName: 'assets/images/soso_biceps.jpg',
name: "Бицепс",
detail: "PRO-версия")
];
}
}
class _ListItem extends StatelessWidget {
_ListItem({this.bgName, this.name, this.detail});
// final int index;
final String bgName;
final String name;
final String detail;
@override
Widget build(BuildContext context) {
return Container(
height: 180.0,
margin: const EdgeInsets.symmetric(
vertical: 1.0,
),
child: new Stack(
children: <Widget>[
new Container(
decoration: new BoxDecoration(
image: new DecorationImage(
image: new AssetImage(bgName),
colorFilter: new ColorFilter.mode(
Colors.black.withOpacity(0.45), BlendMode.darken),
fit: BoxFit.cover,
alignment: Alignment.center),
),
child: new SizedBox.expand(
child: Container(
alignment: Alignment.center,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
new Text(
name,
style: new TextStyle(fontSize: 29.0, color: Colors.white),
),
Padding(
padding: const EdgeInsets.only(top: 12.0),
child: new Text(
detail,
style:
new TextStyle(fontSize: 16.0, color: Colors.white),
),
)
],
),
),
),
),
],
),
);
}
}
我有底部导航。当我进行转换时,我的应用程序经常冻结。在我看来,我应该在一个线程中实现它,我只是不知道如何。
这是我的代码:
public void clickAction(View view) {
ImageButton diaryButton = (ImageButton) findViewById(R.id.diary_button);
ImageButton appointButton = (ImageButton) findViewById(R.id.appoint_button);
ImageButton veriButton = (ImageButton) findViewById(R.id.veri_button);
diaryButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment diaryfragment = new DiaryFragment();
FragmentTransaction ft1 = getSupportFragmentManager().beginTransaction();
ft1.add(R.id.content_frame, diaryfragment);
ft1.commit();
}
}
);
appointButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment appointfragment = new CalendarFragment();
FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
ft2.add(R.id.content_frame, appointfragment);
ft2.commit();
}
}
);
veriButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment verifragment = new AimsFragment();
FragmentTransaction ft3 = getSupportFragmentManager().beginTransaction();
ft3.add(R.id.content_frame, verifragment);
ft3.commit();
}
}
);
}
我想实现一个 Recycler 视图,其中单击一个项目时会出现一个片段。但是 getSupportFragmentManager() 方法对我不起作用,我尝试替换 getActivity() 和 FragmentActivity,但对我没有任何作用。
public class AimsListAdapter extends RecyclerView.Adapter {
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.aims_fragment_list,viewGroup,false);
return new AimsListHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
((AimsListHolder)viewHolder).bindView(i);
}
@Override
public int getItemCount() {
return OurAimsDataForFragment.tittle.length;
}
private class AimsListHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView AimsTextName;
private TextView AimsTextTap;
private ImageView AimsImage;
public AimsListHolder(@NonNull View itemView) {
super(itemView);
AimsTextName = (TextView)itemView.findViewById(R.id.aims_text_name);
AimsTextTap = (TextView) itemView.findViewById(R.id.aims_text_tap);
AimsImage = (ImageView) itemView.findViewById(R.id.aims_image);
itemView.setOnClickListener(this);
}
public void bindView(int position){
AimsTextName.setText(OurAimsDataForFragment.tittle[position]);
AimsTextTap.setText(OurAimsDataForFragment.tap[position]);
AimsImage.setImageResource(OurAimsDataForFragment.picturePath[position]);
}
@Override
public void onClick(View v) {
int position = getAdapterPosition();
switch (position) {
case 1:
Fragment verifragment = new AimsDialogMetkaFragment();
FragmentTransaction ft3 = FragmentActivity.getSupportFragmentManager().beginTransaction();
ft3.add(R.id.content_frame, verifragment);
ft3.commit();
break;
}
}
}
我想在 Fragment 中实现 Bottom Sheet,但 Android Studio 在 OnCreate() 方法中看不到 getSupportFragmentManager() 方法
您需要在其中实现底部工作表的片段
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
* A simple {@link Fragment} subclass.
*/
public class AimsFragment extends Fragment {
public AimsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button showModalBottomSheet = (Button) findViewById(R.id.aim_dialog_modal);
showModalBottomSheet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Initializing a bottom sheet
BottomSheetDialogFragment bottomSheetDialogFragment = new AimsBottomSheetDialogFragment();
//show it
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_aims, container, false);
}
}
底部工作表片段 XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.mederov.timelord.AimsFragment">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<Button
android:id="@+id/as_modal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/logo_splash_margin_endorright"
android:text="@string/author" />
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
实现底部工作表的代码
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.design.widget.CoordinatorLayout;
import android.view.View;
public class AimsBottomSheetDialogFragment extends BottomSheetDialogFragment {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private BottomSheetBehavior.BottomSheetCallback mBottomSheetBehaviorCallback = new BottomSheetBehavior.BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss();
}
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
}
};
@SuppressLint("RestrictedApi")
@Override
public void setupDialog(Dialog dialog, int style) {
super.setupDialog(dialog, style);
View contentView = View.inflate(getContext(), R.layout.aims_dialog_modal, null);
dialog.setContentView(contentView);
CoordinatorLayout.LayoutParams layoutParams =
(CoordinatorLayout.LayoutParams) ((View) contentView.getParent()).getLayoutParams();
CoordinatorLayout.Behavior behavior = layoutParams.getBehavior();
if (behavior != null && behavior instanceof BottomSheetBehavior) {
((BottomSheetBehavior) behavior).setBottomSheetCallback(mBottomSheetBehaviorCallback);
}
}
}
拉出式底页 XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/settings"
android:gravity="center"
android:text="Download"
android:textColor="@android:color/black" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableTop="@drawable/scheldule"
android:gravity="center"
android:text="Upload"
android:textColor="@android:color/black" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/author" />
</LinearLayout>
我想绑定 BottomNagation 和 NagationView。但是“运行”会产生以下内容
E/AndroidRuntime:致命异常:主进程:com.mederov.timelord,PID:24070 java.lang.RuntimeException:无法启动活动 ComponentInfo{com.mederov.timelord/com.mederov.timelord.MainActivity}:android.view。 InflateException:二进制 XML 文件第 38 行:二进制 XML 文件第 38 行:在 android.app.ActivityThread 的 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2785) 上膨胀类 android.support.design.widget.NavigationView 时出错。 handleLaunchActivity(ActivityThread.java:2863) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1596) at android.os.Handler.dispatchMessage(Handler .java:106) 在 android.app.ActivityThread 的 android.os.Looper.loop(Looper.java:164)。main(ActivityThread.java:6541) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal。 os.ZygoteInit.main(ZygoteInit.java:807) 引起:android.view.InflateException:二进制 XML 文件第 38 行:二进制 XML 文件第 38 行:错误膨胀类 android.support.design.widget.NavigationView 引起: android.view.InflateException: Binary XML file line #38: Error inflating class android.support.design.widget.NavigationView 原因:java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance0(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 在 android.view.LayoutInflater.createView(LayoutInflater.java:647) 在 android.view.LayoutInflater.rInflate(LayoutInflater.java:863) 在 android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) 在 android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790) 在 android. view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.rInflate(LayoutInflater.java:866) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate (LayoutInflater.java:515) 在 android.view.LayoutInflater.inflate(LayoutInflater.java:423) 在 android.view.LayoutInflater.inflate(LayoutInflater.java:374) 在 android.support.v7.app.AppCompatDelegateImpl.setContentView( AppCompatDelegateImpl.java:469) 在 android.support.v7.app。AppCompatActivity.setContentView(AppCompatActivity.java:140) 在 com.mederov.timelord.MainActivity.onCreate(MainActivity.java:24) 在 android.app.Activity.performCreate(Activity.java:7033) 在 android.app.Activity.performCreate (Activity.java:7024) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2738) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java: 2863) 在 android.app.ActivityThread.-wrap11(Unknown Source:0) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1596) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在android.app.ActivityThread 上的 android.os.Looper.loop(Looper.java:164)。main(ActivityThread.java:6541) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal。 os.ZygoteInit.main(ZygoteInit.java:807) 原因:java.lang.RuntimeException: android.support.v7.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:215) at android.support.v7 的文档意外结束.view.SupportMenuInflater.inflate(SupportMenuInflater.java:128) 在 android.support.design.widget.NavigationView.inflateMenu(NavigationView.java:264) 在 android.support.design.widget.NavigationView.(NavigationView.java:189)在 android.support.design.widget.NavigationView.(NavigationView.java:104) 在 java.lang.reflect.Constructor。newInstance0(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:334) at android.view.LayoutInflater.createView(LayoutInflater.java:647) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java: 790) 在 android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) 在 android.view.LayoutInflater.rInflate(LayoutInflater.java:863) 在 android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)。 view.LayoutInflater.rInflate(LayoutInflater.java:866) at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) at android.view.LayoutInflater.inflate(LayoutInflater.java:515) at android.view.LayoutInflater.inflate (LayoutInflater.java:423) 在 android.view。在 android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 在 android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 在 com .mederov.timelord.MainActivity.onCreate(MainActivity .java:24) 在 android.app.Activity.performCreate(Activity.java:7033) 在 android.app.Activity.performCreate(Activity.java:7024) 在 android.app. Instrumentation.callActivityOnCreate(Instrumentation.java:1215)在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2738) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2863) 在 android.app.ActivityThread.-wrap11(Unknown Source:0) 在 android.app。活动线程$H。handleMessage(ActivityThread.java:1596) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:164) 在 android.app.ActivityThread.main(ActivityThread.java :6541) 在 java.lang.reflect.Method.invoke(Native Method) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 在 com.android.internal.os.ZygoteInit.main (ZygoteInit.java:807)android.internal.os.ZygoteInit.main(ZygoteInit.java:807)android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
.
XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/fragment_container"
android:layout_above="@id/nav_bar"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include
layout="@layout/toolbar_main"
android:id="@+id/toolbar" />
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="@+id/nav_bar"
app:menu="@menu/bottom_navigation"
android:background="@color/colorWhite"/>
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:menu="@menu/toolbar_menu" />
</RelativeLayout>
</android.support.v4.widget.DrawerLayout>
Java 类
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_bar);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,
drawer,
toolbar,
R.string.nav_open_drawer,
R.string.nav_close_drawer);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
Fragment fragment = new AimsFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.content_frame, fragment);
ft.commit();;
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()){
case R.id.nav_veri:
selectedFragment = new AimsFragment();
break;
case R.id.nav_diary:
selectedFragment = new DiaryFragment();
break;
case R.id.nav_appoint:
selectedFragment = new CalendarFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
Intent intent = null;
switch(id){
case R.id.nav_aims:
fragment = new AimsFragment();
break;
case R.id.nav_reminder:
fragment = new ReminderFragment();
break;
case R.id.nav_statics:
fragment = new StaticsFragment();
break;
case R.id.nav_schedule:
fragment = new ScheduleFragment();
break;
case R.id.nav_project:
fragment = new ProjectFragment();
break;
case R.id.nav_settings:
fragment = new SettingsFragment();
break;
case R.id.nav_info:
fragment = new InfoFragment();
break;
default:
fragment = new AimsFragment();
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
} else {
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
毕业典礼
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.mederov.timelord"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
buildToolsVersion '28.0.3'
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
}
菜单
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_aims"
android:icon="@drawable/idea_aims"
android:title="@string/nav_aims"
android:checked="true" />
<item
android:id="@+id/nav_reminder"
android:icon="@drawable/reminder"
android:title="@string/nav_reminder" />
<item
android:id="@+id/nav_statics"
android:icon="@drawable/statics"
android:title="@string/nav_statics" />
<item
android:id="@+id/nav_schedule"
android:icon="@drawable/scheldule"
android:title="@string/nav_schedule" />
<item
android:id="@+id/nav_project"
android:icon="@drawable/project"
android:title="@string/nav_project" />
</group>
<menu>
<item
android:id="@+id/nav_settings"
android:icon="@drawable/settings"
android:title="@string/nav_settings" />
<item
android:id="@+id/nav_info"
android:icon="@drawable/info"
android:title="@string/nav_info"/>
</menu>
</menu>
帮我解决这个问题,我已经坐了3天了,我不明白这是怎么回事)