2016-03-28 2 views
0

Я хочу добавить две кнопки ниже списка списка, но он не работает, тогда как если я добавлю эти кнопки выше списка, он отлично работает, почему? ЖурналДобавление кнопки ниже listview не работает, в то время как добавление выше работает отлично в android

ошибка:

03-28 07:24:23.610: I/dalvikvm-heap(3296): Grow heap (frag case) to 4.215MB for 1127536-byte allocation 
03-28 07:24:23.650: D/dalvikvm(3296): GC_FOR_ALLOC freed 3K, 5% free 4248K/4428K, paused 33ms, total 34ms 
03-28 07:24:23.790: D/AndroidRuntime(3296): Shutting down VM 
03-28 07:24:23.790: W/dalvikvm(3296): threadid=1: thread exiting with uncaught exception (group=0xb1a3bba8) 
03-28 07:24:23.810: E/AndroidRuntime(3296): FATAL EXCEPTION: main 
03-28 07:24:23.810: E/AndroidRuntime(3296): Process: com.example.ex3dynamiclist, PID: 3296 
03-28 07:24:23.810: E/AndroidRuntime(3296): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ex3dynamiclist/com.example.ex3dynamiclist.MainActivity}: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.ListView 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.ActivityThread.access$800(ActivityThread.java:135) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.os.Handler.dispatchMessage(Handler.java:102) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.os.Looper.loop(Looper.java:136) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.ActivityThread.main(ActivityThread.java:5017) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at java.lang.reflect.Method.invokeNative(Native Method) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at java.lang.reflect.Method.invoke(Method.java:515) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at dalvik.system.NativeStart.main(Native Method) 
03-28 07:24:23.810: E/AndroidRuntime(3296): Caused by: java.lang.ClassCastException: android.widget.Button cannot be cast to android.widget.ListView 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at com.example.ex3dynamiclist.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:64) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.Activity.performStart(Activity.java:5241) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168) 
03-28 07:24:23.810: E/AndroidRuntime(3296):  ... 11 more 
03-28 07:24:26.240: I/Process(3296): Sending signal. PID: 3296 SIG: 9 

.xml,

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.ex3dynamiclist.MainActivity$PlaceholderFragment" > 

    <ListView 
     android:id="@+id/mobile_list" 
     android:layout_width="match_parent" 
     android:layout_height="0dip" 
     android:layout_weight="1" /> 

    <LinearLayout 
     android:id="@+id/LinearLayout2" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <Button 
      android:id="@+id/addBtn" 
      android:layout_width="0px" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:onClick="addItems" 
      android:text="Add Item" /> 

     <Button 
      android:id="@+id/removeBtn" 
      android:layout_width="0px" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:onClick="removeItems" 
      android:text="Remove selected" /> 
    </LinearLayout> 

</LinearLayout> 

.Java FILE

package com.example.ex3dynamiclist; 

import android.support.v7.app.ActionBarActivity; 
import android.support.v7.app.ActionBar; 
import android.support.v4.app.Fragment; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Adapter; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.os.Build; 

public class MainActivity extends ActionBarActivity { 

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

     if (savedInstanceState == null) { 
      getSupportFragmentManager().beginTransaction() 
        .add(R.id.container, new PlaceholderFragment()).commit(); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 

     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 
     String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS","Ubuntu","Windows7","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X","Max OS X"}; 
     public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

      View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(),R.layout.activity_listview, mobileArray); 
      ListView listView = (ListView) rootView.findViewById(R.id.mobile_list); 
      listView.setAdapter(adapter); 
      return rootView; 
     } 
    } 

    public void addItems(View view){ 
     Log.d("DEBUG","Add Items Reached"); 
    } 

    public void removeItems(View view){ 
     Log.d("DEBUG","Remove Items Reached"); 
    } 

} 
+0

напишите свой файл java .. !! – Nils

+1

Очистить и перестроить проект проверить эту строку ClassCastException: android.widget.Button не может быть добавлен в android.widget.ListView. –

+0

Проблема заключается в 'com.example.ex3dynamiclist.MainActivity $ PlaceholderFragment.onCreateView (MainActivity.java:64)'. Не могли бы вы поделиться своим методом onCreate? Вероятно, вы зависите от порядка детей внутри линейной очереди. Вместо этого войдите в список, используя свой идентификатор. –

ответ

1

используйте приведенный ниже код xml, и он обязательно сработает.

Объяснение

вы первым добавили ListView, а затем кнопки и которые делают путаницу относительно высоты в макете. поэтому сначала добавьте кнопки, а затем список.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 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:gravity="bottom" 
app:layout_behavior="@string/appbar_scrolling_view_behavior" 
tools:context="com.afixi.prasenjeetpati.listviewinsidescrollview.Main2Activitytryyyy" 
tools:showIn="@layout/activity_main2_activitytryyyy"> 

<LinearLayout 
    android:id="@+id/LinearLayout2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:layout_centerHorizontal="true" 
    android:orientation="horizontal"> 

    <Button 
     android:id="@+id/addBtn" 
     android:layout_width="0dp" 
     android:layout_weight="1" 
     android:layout_height="wrap_content" 
     android:layout_alignBottom="@+id/linearLayout2" 
     android:text="add item" /> 

    <Button 
     android:layout_width="0dp" 
     android:layout_weight="1" 
     android:layout_height="wrap_content" 
     android:text="remove item" 
     android:id="@+id/removeBtn" /> 
</LinearLayout> 

<ListView 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/mobile_list" 
    android:layout_alignParentTop="true" 
    android:layout_above="@+id/LinearLayout2"/> 
</RelativeLayout> 
+0

рад, что я могу вам помочь. –

0

Изменение родительского LinearLayout к RelativeLayout, изменение mobile_list-х и LinearLay out2's height to wrap_content, удалить вес из mobile_list и добавить

android:layout_alignParentBottom="true" 

LinearLayout2. Как показано ниже:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 

tools:context="com.example.ex3dynamiclist.MainActivity$PlaceholderFragment" > 

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

<LinearLayout 
    android:id="@+id/LinearLayout2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentBottom="true" 
    android:orientation="horizontal" > 

    <Button 
     android:id="@+id/addBtn" 
     android:layout_width="0px" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:onClick="addItems" 
     android:text="Add Item" /> 

    <Button 
     android:id="@+id/removeBtn" 
     android:layout_width="0px" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:onClick="removeItems" 
     android:text="Remove selected" /> 
</LinearLayout> 

0

Ваш файл XML должен иметь что-то вроде ниже код

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context="com.example.ex3dynamiclist.MainActivity$PlaceholderFragment" > 

    <ListView 
     android:id="@+id/mobile_list" 
     android:layout_width="match_parent" 
     android:layout_height="0dip" 
     android:layout_weight="0.8" /> 

    <LinearLayout 
     android:id="@+id/LinearLayout2" 
     android:layout_width="match_parent" 
     android:layout_height="0dip" 
     android:orientation="horizontal" 
     android:layout_weight="0.2"> 

     <Button 
      android:id="@+id/addBtn" 
      android:layout_width="0dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:onClick="addItems" 
      android:text="Add Item" /> 


     <Button 
      android:id="@+id/removeBtn" 
      android:layout_width="0dip" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:onClick="removeItems" 
      android:text="Remove selected" /> 
    </LinearLayout> 

</LinearLayout> 

Rest назначить кнопку и ListView идентификаторы правильно в вашем фрагменте. И установите onClickListeners и адаптер как и как нужно. Также, если вы хотите поместить кнопки над списком, просто отрежьте линейный макет, содержащий две кнопки, и вставьте его над списком.

Смежные вопросы