2013-11-17 5 views
1

, пожалуйста, помогите Когда я запускаю действие ListFragment actitivy и нажимаю на фрагмент (Buick или Mazda), макет фрагмента, на который я щелкнул, должен заменить и закрыть весь экран, но контейнер, содержащий список автомобилей, остается на экране, и ниже показана его структура фрагмента. Как я могу заменить макет моего фрагмента на весь экран?Фрагмент не покрывает весь экран

Я не смог опубликовать свое AVD-изображение, показывающее экран, потому что у меня недостаточно репутаций, чтобы сделать , но экран показывался ниже, когда я нажал на первый элемент в списке.

Buick Mazda

Здравствуйте! Это Бьюик

мой Mainactivity

package in.cars.demo; 

import android.app.Activity; 
import android.os.Bundle; 

public class CarsMainActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
    } 
} 

Моя ListFragment активность

package in.cars.demo; 

import android.app.Fragment; 
import android.app.FragmentTransaction; 
import android.app.ListFragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.Toast; 

public class CarsList extends ListFragment { 

    String[] cars = new String[] { "Buick", "Mazda" }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ListAdapter myListAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, cars); 
     setListAdapter(myListAdapter); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.cars_container, container, false); 
    } 

    @Override 
    public void onListItemClick(ListView l, View v, int position, long id) { 
     Toast.makeText(getActivity(), getListView().getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show(); 
     switch (position) { 
     case 0: 
      Fragment fragment1 = new Fragment1(); 
      FragmentTransaction transaction1 = getFragmentManager().beginTransaction(); 
      transaction1.replace(R.id.car_fragment, fragment1); 
      transaction1.addToBackStack(null); 
      transaction1.commit(); 
      break; 
     case 1: 
      Fragment fragment2 = new Fragment2(); 
      FragmentTransaction transaction2 = getFragmentManager().beginTransaction(); 
      transaction2.replace(R.id.car_fragment, fragment2); 
      transaction2.addToBackStack(null); 
      transaction2.commit(); 
      break; 
     } 
    } 
} 

Fragment1

package in.cars.demo; 

import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

public class Fragment1 extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment1, container, false); 
    } 
} 

FRAGMENT2

package in.cars.demo; 

import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

public class Fragment2 extends Fragment { 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment2, container, false); 
    } 
} 

main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <fragment 
     android:id="@+id/car_fragment" 
     android:name="in.cars.demo.CarsList" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     /> 
</LinearLayout> 

cars_container.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:paddingLeft="4dp" 
     android:paddingRight="4dp"> 

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

fragment1.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" > 
    <TextView 
     android:id="@+id/frag1TV" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Hello! It's a Buick" /> 
</LinearLayout> 

fragment2.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" > 
    <TextView 
     android:id="@+id/frag2TV" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Hello! It's a Mazda" /> 
</LinearLayout> 
+0

Спасибо Стив, я сделал именно так, как вы предложили, и она работала. вы здоровы. –

ответ

1

Проблема заключается в том, что вы устанавливаете layout_height вашего фрагмента wrap_content в вашем main.xml. Видимый размер будет уменьшен до фактического размера фрагмента.

Изменить его match_parent, чтобы заполнить весь экран:

... 
<fragment 
    android:id="@+id/car_fragment" 
    android:name="in.cars.demo.CarsList" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    /> 
... 

Кроме использования match_parent вместо fill_parent в приложениях с уровнем API 8+. См. Это question для получения дополнительной информации.

Edit:

Вы должны изменить контейнер для фрагментов. Фрагмент, установленный с тегом, будет статическим. В дополнение к этому контейнеру будет установлен каждый фрагмент. Для динамического подхода используйте FrameLayout. Теперь вы можете заменить фрагмент, который был там раньше.

... 
<FrameLayout 
    android:id="@+id/car_fragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
/> 
... 

Чтобы показать свой автомобиль, вам необходимо выполнить транзакцию с фрагментами в своей деятельности.

getFragmentManager()/getSupportFragmentManager() 
.beginTransaction() 
.replace(R.id.car_fragment, new CarsList()) 
.addToBackstack(null) 
.commit(); 
+0

Я перешел на match_parent, и это не исправило. Я также заметил, что я импортировал import android.app.Fragment вместо android.support.v4.app.Fragment, поэтому я изменил все классы, чтобы импортировать файл android.support.v4.app.Fragment, и это все еще не исправило. –

+0

@SulimanGabhourz См. Мое редактирование –

0

Немного поздно, но, возможно, я помогу кому-то еще.Проблема заключается в «фрагменте» в вашем файле xml-файла активности (main.xml). Вы должны изменить:

<fragment 
    android:id="@+id/car_fragment" 
    android:name="in.cars.demo.CarsList" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"/> 

в

<fragment 
    android:id="@+id/car_fragment" 
    android:name="in.cars.demo.CarsList" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"/> 
Смежные вопросы