爱哭的衰小孩 2020-12-16 23:56 采纳率: 100%
浏览 60
已采纳

刚开始学android看第一行代码照敲酷欧天气报错打不开活动有大佬拉一把不?

具体报错信息是java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coolweather.android/com.coolweather.android.MainActivity}: android.view.InflateException: Binary XML file line #6 in com.coolweather.android:layout/activity_main: Binary XML file line #6 in com.coolweather.android:layout/activity_main: Error inflating class fragment

搜了半天貌似一般是导包问题和路径  但是看了好久都没觉得有问题  打不开活动 调试也是在main活动的设置布局那直接闪退   应该是碎片的问题  代码如下



<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/choose_area_fragment"
        android:name="com.coolweather.android.ChooseAreaFragment"/>

</FrameLayout>

继承Fragment的活动

package com.coolweather.android;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import db.City;
import db.County;
import db.Province;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import util.HttpUtil;
import util.Utility;


public class ChooseAreaFragment extends  Fragment {
    public static final int LEVEL_PROVINCE = 0;
    public static final  int LEVEL_CITY = 1;
    public static final int Level_COUNTY = 2;
    private ProgressDialog progressDialog;
    private TextView titleText;
    private Button backButton;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<>();
    /*
    省列表
     */
    private List<Province> provinceList;
    /*
    市列表
     */
    private List<City> cityList;
    /*
    县列表
     */
    private List<County> countyList;
    /*
    选中的省份
     */
    private Province selectedProvince;
    /*
    选中的城市
     */
    private City selectedCity;
    /*
    当前选中的级别
     */
    private int currentLevel;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        //实例化各个组件
        View view = inflater.inflate(R.layout.choose_area, container, false);
        titleText = (TextView) view.findViewById(R.id.title_text);
        backButton = (Button) view.findViewById(R.id.back_button);
        listView = (ListView)view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            //给菜单设置点击事件
            public void onItemClick(AdapterView<?>parent, View view, int position, long id){
                if(currentLevel == LEVEL_PROVINCE){
                    selectedProvince = provinceList.get(position);
                    queryCities();
                }
                else if(currentLevel == LEVEL_CITY){
                    selectedCity = cityList.get(position);
                    queryCounties();
                }
            }
        });
        //backButton设置点击事件
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(currentLevel == Level_COUNTY){
                    queryCities();
                }
                else if (currentLevel == LEVEL_CITY){
                    queryProvinces();
                }
            }
        });
        queryProvinces();//调用方法加载省级数据
    }
    /*
    查询全国所有的省份,优先从数据库查询,如果没查询到再去服务器上查询
     */
    private void queryProvinces(){
        titleText.setText("中国");//把头布局标题设置为中国
        backButton.setVisibility(View.GONE);    //隐藏返回按钮   因为此时已经是省级列表,没有上一级页面了
        provinceList = LitePal.findAll(Province.class);//DataSupport已经过时   这里从数据库读取省级数据
        //如果从数据库读取到了数据
        if (provinceList.size() > 0){
            dataList.clear();           //清空县集合里元素
            //下面循环添加县名字
            for (Province province : provinceList){
                dataList.add(province.getProvinceName());
            }
            adapter.notifyDataSetChanged();//记住你划到的位置,重新加载数据的时候不会改变位置,只是改变了数据;
            listView.setSelection(0);           //将第一个数据项设置在最上面
            currentLevel =LEVEL_PROVINCE;       //将当前级别设置为省级
        }
        //如果数据库没有,就去服务器查询
        else {
            String address = "http://guolin.tech/api/china";
            queryFromServer(address, "province");
        }
    }
    /*
    查询选中省内所有的市,优先从数据库查询,如果没查询到再去服务器上查询
     */
    private void queryCities(){
        titleText.setText(selectedProvince.getProvinceName());
        backButton.setVisibility(View.VISIBLE);     //设置按钮为可见,因为有上个界面
        cityList = LitePal.where("provinced = ?", String.valueOf(selectedProvince.getId())).find(City.class);
        if (cityList.size() > 0){
            dataList.clear();
            for (City city : cityList){
                dataList.add(city.getCityName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_CITY;
        }
        else {
            int provinceCode = selectedProvince.getProvinceCode();
            String address = "http://guolin.tech/api/china" + provinceCode;
            queryFromServer(address, "city");
        }
    }
    /*
    查询选中市内所有的县,优先从数据库查询,如果没用查询到再去服务器上查询
     */
    private void queryCounties(){
        titleText.setText(selectedCity.getCityName());
        backButton.setVisibility(View.VISIBLE);
        countyList = LitePal.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
        if(countyList.size() > 0){
            dataList.clear();
            for (County county : countyList){
                dataList.add(county.getCountyName());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = Level_COUNTY;
        }
        else{
            int provinceCode = selectedProvince.getProvinceCode();
            int cityCode = selectedCity.getCityCode();
            String address = "http://guolin.tech/api/china" + provinceCode + "/" + cityCode;
            queryFromServer(address, "county");
        }
    }
    /*
    根据传入的地址和类型从服务器上查询省市县数据
     */
    private void queryFromServer(String address, final String type){
        showProgressDialog();
        //调用HttpUtil的sendOkHttpRequest()方法来向服务器发送请求,响应的数据会回调到里面的onResponse方法中
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //通过runOnUiThread()方法回到主线程处理逻辑,因为queryProvinces()方法里将第一个数据项设置在顶部的操作是UI操作,必须在主线程操作
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();     //解析响应的数据构造一个新String
                boolean result = false;             //设置结果为false
                if ("province".equals(type)){
                    result = Utility.handleProvinceResponse(responseText);      //右边是将数据传到该方法里解析并且处理服务器返回的省级数据返回一个boolean值
                }
                else if ("city".equals(type)){
                    result = Utility.handleCityResponse(responseText, selectedProvince.getId());
                }
                else if ("county".equals(type)){
                    result = Utility.handleCountyResponse(responseText, selectedCity.getId());
                }
                //解析成功时
                if (result){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)){
                                queryProvinces();                   //如果传入的数据要求查省,调用queryProvinces()方法去服务器查找
                            }
                            else if ("city".equals(type)){
                                queryCities();
                            }
                            else if ("county".equals(type)){
                                queryCounties();
                            }
                        }
                    });
                }
            }
        });
    }

    /*
    显示对话框
     */
    private void showProgressDialog(){
        if(progressDialog == null){
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    private void closeProgressDialog(){
        if(progressDialog != null){
            progressDialog.dismiss();
        }
    }
}

继承Fragment的类加载的布局choose_area

<?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"
    android:background="#fff">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary">

        <TextView
            android:id="@+id/title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:textColor="#fff"
            android:textSize="20sp" />

        <Button
            android:id="@+id/back_button"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:background="@drawable/ic_back" />
    </RelativeLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/list_view"/>

</LinearLayout>

还有另外两个类一个是解析服务器返回数据一个是发送请求  应该没问题  我就不发上来了  不知道碎片哪里错了。。。

有大佬救救快入土的萌新吗0.0

  • 写回答

3条回答 默认 最新

  • 无厘头编程 2020-12-17 01:30
    关注

    Fragment 都是孩子,孩子他妈,Activity,在那?FragmentManager 就是管孩子的那根鞭子。发,发,发,听着爽快,好使。这是老妈那里的指令:

            val fragment = WelcomeFragment.newInstance()
            lgd(tag+"Show Welcome Fragment.")
            val mTransaction = fragmentManager.beginTransaction()
            mTransaction.add(R.id.eventContainer, fragment)
            mTransaction.commit()

    Transaction 就是 发的单子,一次性的,不能复用。commit(),就是推孩子 上 屏幕了,走不走?一点就踢出去了,见到孩子,激动啊!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测