2015-07-15 2 views
0

У меня есть Layout с двумя ListView в Android. Первый вид списка имеет пользовательский адаптер с тремя TextView. Второй ListView также имеет обычай Adapter с двумя TextView. Сначала второй ListView невидим. При щелчке по любому TextView первого ListView, второй ListView должен стать видимым.Как изменить видимость ListView внутри пользовательского адаптера другого ListView?

customAdapter В классе первого списка View у меня есть OnClick слушателя для TextView-х, где я поставил visiblity второго ListView к true.

Видимость правильно изменена, которую я вижу в своих журналах. Но это не отражено в пользовательском интерфейсе.

Основной макет с двумя видами списка search_by_bus_id.xml:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:map="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:background="@drawable/bg_dots" > 

    <FrameLayout 
     android:id="@+id/listmain" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" > 

     <ListView 
      android:id="@+id/listbusid" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="1" 
      android:divider="@android:color/transparent" 
      android:dividerHeight="10.0sp" 
      android:scrollingCache="true" /> 
    </FrameLayout> 

    <FrameLayout 
     android:id="@+id/about" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 

     android:background="#60000000" 
     > 

     <ListView 
      android:id="@+id/aboutBus" 
      android:layout_width="wrap_content" 
      android:layout_height="458dp" 
      android:layout_weight="1" 
      android:divider="@android:color/transparent" 
      android:dividerHeight="10.0sp" > 
     </ListView> 

    </FrameLayout> 

</RelativeLayout> 

ListItem для первого ListView (list_item3.xml)

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <android.support.v7.widget.CardView 
     xmlns:card_view="http://schemas.android.com/apk/res-auto" 
     android:id="@+id/card_view2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_margin="15dp" 
     android:background="@color/blue" 
     card_view:cardCornerRadius="8dp" > 

     <RelativeLayout 
      xmlns:card_view="http://schemas.android.com/apk/res-auto" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:background="#42BF51" 
      android:orientation="vertical" > 

      <TextView 
       android:id="@+id/BusNo" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_margin="15dp" 
       android:text="124" 
       android:textAppearance="?android:attr/textAppearanceLarge"/> 

      <TextView 
       android:id="@+id/Bus1Time" 
       android:layout_margin="15dp" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignParentRight="true" 
       android:layout_alignParentTop="true" 
       android:text="4:28pm" 
       android:textAppearance="?android:attr/textAppearanceMedium" /> 

      <TextView 
       android:id="@+id/Bus2Time" 
       android:layout_margin="15dp" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_alignParentRight="true" 
       android:layout_below="@+id/Bus1Time" 
       android:text="4:28pm" 
       android:textAppearance="?android:attr/textAppearanceMedium"/> 
     </RelativeLayout> 
    </android.support.v7.widget.CardView> 

</FrameLayout> 

Адаптер класса для первого LsstView

public class BusAdapter extends ArrayAdapter<Bus> implements OnClickListener { 

    private ArrayList<Bus> objects; 
    static BusDetailsAdapter bus_details_adapter; 
    static ArrayList<AboutBus> busdetails = new ArrayList<AboutBus>(); 

    public BusAdapter(Context context, int textViewResourceId, 
      ArrayList<Bus> objects) { 
     super(context, textViewResourceId, objects); 
     this.objects = objects; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 

     View v = convertView; 

     if (v == null) { 
      LayoutInflater inflater = (LayoutInflater) getContext() 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      v = inflater.inflate(R.layout.list_item3, null); 

     } 

     Bus i = objects.get(position); 

     if (i != null) { 

      TextView busNo = (TextView) v.findViewById(R.id.BusNo); 
      TextView departure1 = (TextView) v.findViewById(R.id.Bus1Time); 
      TextView departure2 = (TextView) v.findViewById(R.id.Bus2Time); 

      if (busNo != null) { 
       busNo.setText(i.getBus()); 
      } 
      if (departure1 != null) { 
       departure1.setText(i.getDeparture1()); 
      } 
      if (departure2 != null) { 
       departure2.setText(i.getDeparture2()); 
      } 

      busNo.setTag(i); 

      busNo.setOnClickListener(this); 

      departure1.setTag(i); 
      departure1.setOnClickListener(this); 

      departure2.setTag(i); 

      departure2.setOnClickListener(this); 

     } 

     // the view must be returned to our activity 
     return v; 

    } 

    @Override 
    public void onClick(View v) { 

     LayoutInflater mInflater = (LayoutInflater) getContext() 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View v2 = (View) mInflater.inflate(R.layout.search_by_bus_id, null); 

     ListView listView2 = (ListView) v2.findViewById(R.id.aboutBus); 

     switch (v.getId()) { 

     case R.id.BusNo: 

      if (listView2 != null) { 



       listView2.setVisibility(View.VISIBLE); 

       Log.d("Visibilty", " " + listView2.getVisibility()); 
      } 

      this.notifyDataSetChanged(); 

      break; 
     case R.id.Bus1Time: 

      if (listView2 != null) { 

       listView2.setVisibility(View.VISIBLE); 


       Log.d("Visibilty", " " + listView2.getVisibility()); 
      } 

      this.notifyDataSetChanged(); 

      break; 
     default: 
      break; 
     } 

    } 

} 

адаптер для listView2 :

public class BusDetailsAdapter extends ArrayAdapter<AboutBus> { 

private ArrayList<AboutBus> objects; 

public BusDetailsAdapter(Context context, int textViewResourceId, 
     ArrayList<AboutBus> objects) { 

    super(context, textViewResourceId, objects); 
    this.objects = objects; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 

    // assign the view we are converting to a local variable 
    View v = convertView; 

    if (v == null) { 
     LayoutInflater inflater = (LayoutInflater) getContext() 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = inflater.inflate(R.layout.list_item4, null); 
    } 


    AboutBus i = objects.get(position); 

    if (i != null) { 



     TextView Operator = (TextView) v 
       .findViewById(R.id.Operator); 
     TextView Load = (TextView) v 
       .findViewById(R.id.Load); 

     if (Operator != null) { 
      Operator.setText(i.getOperator()); 
     } 
     if (Load != null) { 
      Load.setText(i.getLoad()); 
     } 

    } 

    return v; 

} 

}

ListItem для 2-го ListView (list_item4.xml):

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
xmlns:card_view="http://schemas.android.com/apk/res-auto" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" > 

<RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="@color/green" 
     android:orientation="vertical" > 

     <TextView 
      android:id="@+id/OperatorText" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_margin="15dp" 
      android:text="Operator : " 
      android:textAppearance="?android:attr/textAppearanceLarge"/> 

     <TextView 
      android:id="@+id/Operator" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_toRightOf="@+id/OperatorText" 
      android:layout_margin="15dp" 
      android:text="dummy" 
      android:textAppearance="?android:attr/textAppearanceLarge"/> 


      <TextView 
      android:id="@+id/LoadText" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/OperatorText" 
      android:layout_margin="15dp" 

      android:text="Load : " 
      android:textAppearance="?android:attr/textAppearanceLarge"/> 

     <TextView 
      android:id="@+id/Load" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignLeft="@+id/Operator" 
      android:layout_below="@+id/Operator" 
      android:layout_marginTop="15dp" 
      android:text="dummy" 
      android:textAppearance="?android:attr/textAppearanceLarge" /> 

    </RelativeLayout> 

Часть OnClick:

@Override 
public void onClick(View v) { 

    LayoutInflater mInflater = (LayoutInflater) getContext() 
      .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    View v2 = (View) mInflater.inflate(R.layout.search_by_bus_id, null); 

    if (BusAdapter.listView2 == null) { 

     BusAdapter.listView2 = (ListView) v2 
       .findViewById(R.id.aboutBus); 
    } 


    Bus i = (Bus) v.getTag(); 

    BusAdapter.busdetails.clear(); 

    switch (v.getId()) { 

    case R.id.BusNo: 

     AboutBus ab1 = new AboutBus("dummy", "dummy"); 

     BusAdapter.busdetails.add(ab1); 

     BusAdapter.bus_details_adapter = new BusDetailsAdapter(
       getContext(), R.layout.list_item4, BusAdapter.busdetails); 

     if (listView2 != null) { 

      listView2.setVisibility(View.VISIBLE); 
     } 

     this.notifyDataSetChanged(); 

     break; 
    case R.id.Bus1Time: 
    ....... 
    .....continued 
+0

У вас есть «основной макет» с двумя списками ListView, но внутри вашего ** BusAdapter ** метода onClick ваш раздув того же макета с двумя ListViews, который ... неправильно. Предполагается, что ваш «основной макет» в действии или фрагменте, вы должны обеспечить обратную связь и изменить видимость там, вы не можете раздуть ту же макет. – Marko

+0

Спасибо Марко. Работал как шарм :) –

ответ

0

Вы должны попытаться найти ListView элемент из основного контейнера объявление раздувания другого макета.

Что я имею в виду, сделайте findViewById на исходном объекте представления, переданном из действия/фрагмента в адаптер.

+0

Спасибо за ваш ответ.Но второй вид списка отображается поверх первого списка. Я пробовал это в main_activity, и он отображается правильно. Но когда я изменяю видимость в адаптере для 1-го списка, он не работает –

+0

, но где связанный адаптер для указания набора данных для второго списка? Как это сделать данные без его адаптера – borax12

+0

Данные установлены: AboutBus ab2 = new AboutBus (i.getOperator(), i.getLoad2()); \t \t \t BusAdapter.busdetails.add (ab2); \t \t \t BusAdapter.bus_details_adapter = новый BusDetailsAdapter ( \t \t \t \t \t getContext(), R.layout.list_item4, BusAdapter.busdetails); –

0

Я думаю, что его, потому что ListView Он принадлежит верстки деятельности и вы не передавая ссылки на деятельность, чтобы сделать видимость или не может быть, ваша попытка что-то вроде этого

adapter = new (ActivityMain.this, some paramnts) 

и адаптер принимает ссылку и изменить видимость

+0

Спасибо за ваш ответ. В моей основной деятельности у меня есть bus_adapter = новый BusAdapter (это, R.layout.list_item3, шина). Не понял, что вы хотите, чтобы я изменился здесь. –

+0

ваш listview создаются на xml-адаптере o в xml активности? –

+0

попробуйте это, в своей деятельности создайте такой метод, как это public static void changeList() {измените видимость вашего списка} и в адаптере, когда щелкните по тексту, вызовите этот метод, как этот MainActivity.changeList(); и все это –

0

Я думаю, вы должны объявить оба FrameLayout из search_by_bus_id.xml и использовать это в связанном Java-файле, чтобы отключить и включить ListView. Просто сохраните Visible и LinearLayout и попробуйте изменить Visibilty из Framelayout в файле Java

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