错误:java.lang.ClassCastException:android.view.View无法强制转换为android.view.ViewGroup

时间:2018-01-30 20:03:17

标签: java android xml listview

我试图将数据库转换为ListView,并在点击时显示更多信息,但是一旦我添加了可扩展功能,我就开始在标题中收到错误。< / p>

这是我的list_item.xml,似乎是问题的根源:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="@dimen/activity_horizontal_margin">
        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="2dip"
            android:textColor="@color/colorAccent"/>

        <View
            android:layout_width="0px"
            android:layout_height="0px"
            android:id="@+id/expandable">
            <TextView
                android:id="@+id/description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#5d5d5d"
                android:textStyle="bold"/>
            <TextView
                android:id="@+id/email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#5d5d40"
                android:textStyle="bold" />
            <TextView
                android:id="@+id/telephone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#5d5d40"
                android:textStyle="bold" />
        </View>
    </LinearLayout>

这里是MainActivity2.java(临时名称):

public class MainActivity2 extends Activity {

    private String TAG = MainActivity2.class.getSimpleName();
    private ListView lv;
    private View ex;

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();

        ex = findViewById(R.id.expandable);

        lv.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView parentView, View childView,
                                       int position, long id)
            {
                expand(ex);
            }

            public void onNothingSelected(AdapterView parentView) {

            }
        });



    }

    public static void expand(final View v) {
        v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        final int targetHeight = v.getMeasuredHeight();

        // Older versions of android (pre API 21) cancel animations for views with a height of 0.
        v.getLayoutParams().height = 1;
        v.setVisibility(View.VISIBLE);
        Animation a = new Animation()
        {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                v.getLayoutParams().height = interpolatedTime == 1
                        ? LinearLayout.LayoutParams.WRAP_CONTENT
                        : (int)(targetHeight * interpolatedTime);
                v.requestLayout();
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        // 1dp/ms
        a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density));
        v.startAnimation(a);
    }

    public static void collapse(final View v) {
        final int initialHeight = v.getMeasuredHeight();

        Animation a = new Animation()
        {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if(interpolatedTime == 1){
                    v.setVisibility(View.GONE);
                }else{
                    v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                    v.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        // 1dp/ms
        a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
        v.startAnimation(a);
    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(MainActivity2.this,"Json Data is downloading",Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();
            // Making a request to url and getting response
            String url = "https://s3-eu-west-1.amazonaws.com/tyi-work/Work_Experience.json";
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("work");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);
                        String id = c.getString("id");
                        String name = c.getString("name");
                        String email = c.getString("email");
                        String address = c.getString("address");
                        String telephone = c.getString("telephone");

                        // Phone node is JSON Object
                        String description = c.getString("description");
                        String agerange = c.getString("agerange");
                        String county = c.getString("county");
                        String category = c.getString("category");
                        String website = c.getString("website");

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("description", description);
                        contact.put("name", name);
                        contact.put("email", email);
                        contact.put("telephone", telephone);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(MainActivity2.this, contactList,
                    R.layout.list_item, new String[]{ "email","description","name"},
                    new int[]{R.id.email, R.id.description, R.id.name});
            lv.setAdapter(adapter);
        }
    }
}

如果需要更多信息,我很乐意提供。

提前谢谢

编辑:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.teamplum.projectapple, PID: 12076
                  java.lang.ClassCastException: android.view.View cannot be cast to android.view.ViewGroup
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:826)
                      at android.view.LayoutInflater.rInflate(LayoutInflater.java:828)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:523)
                      at android.view.LayoutInflater.inflate(LayoutInflater.java:425)
                      at android.widget.SimpleAdapter.createViewFromResource(SimpleAdapter.java:121)
                      at android.widget.SimpleAdapter.getView(SimpleAdapter.java:114)
                      at android.widget.AbsListView.obtainView(AbsListView.java:2481)
                      at android.widget.ListView.measureHeightOfChildren(ListView.java:1289)
                      at android.widget.ListView.onMeasure(ListView.java:1197)
                      at android.view.View.measure(View.java:17970)
                      at android.widget.RelativeLayout.measureChild(RelativeLayout.java:816)
                      at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:561)
                      at android.view.View.measure(View.java:17970)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
                      at android.view.View.measure(View.java:17970)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1723)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:785)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:654)
                      at android.view.View.measure(View.java:17970)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5710)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:465)
                      at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2755)
                      at android.view.View.measure(View.java:17970)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2438)
                      at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1418)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1642)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1296)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6742)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:826)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:629)
                      at android.view.Choreographer.doFrame(Choreographer.java:597)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:812)
                      at android.os.Handler.handleCallback(Handler.java:815)
                      at android.os.Handler.dispatchMessage(Handler.java:104)
                      at android.os.Looper.loop(Looper.java:194)
                      at android.app.ActivityThread.main(ActivityThread.java:5931)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:987)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782)

1 个答案:

答案 0 :(得分:1)

此错误表示您将视图放在<View>中。将此视图更改为ViewGroup(例如linearLayoutRelativeLayout),您的问题就会消失。

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">
    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"      <!-- edit this height and width-->
                                            <!--also add orientation-->
        android:id="@+id/expandable">
        <TextView
            android:id="@+id/description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#5d5d5d"
            android:textStyle="bold"/>
        <TextView
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#5d5d40"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/telephone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#5d5d40"
            android:textStyle="bold" />
    </LinearLayout>
</LinearLayout>