#android #android-layout #android-fragments #android-view
#Android #android-макет #android-фрагменты #android-просмотр
Вопрос:
У меня есть фрагмент, который имеет горизонтальный вид прокрутки. Я хочу добавить еще один фрагмент в этот scrollview. Как я могу это сделать?
Вот мой первый фрагмент
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="220dp"
android:background="@drawable/arrow_bg">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@ id/horizontalScrollView"
android:layout_marginTop="15dp" >
<LinearLayout
android:id="@ id/offerLayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Я пытаюсь добавить приведенный ниже фрагмент в scrollview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="174dp"
android:layout_height="214dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="HEALTH"
android:id="@ id/offerTitle"
android:capitalize="characters" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/offer_image_text_bg">
<ImageView
android:layout_width="wrap_content"
android:layout_height="135dp"
android:id="@ id/offerIcon"
android:src="@drawable/health_img"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@ id/favLayout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@ id/ratingBar"
android:numStars="5"
android:rating="4"
android:isIndicator="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
style="@style/ratingBarStyle"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginRight="5dp"
android:id="@ id/favIcon"
android:src="@drawable/like_icon"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_below="@ id/favLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@ id/txt_OfferTitle2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@ id/txt_OfferDesc" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
Это код, который я использую для того же
private void loadSelectedOffers() {
for(int i=0;i<3;i )
{
OfferItemFragment offerItem = new OfferItemFragment();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
offerItem.getView().setLayoutParams(params);
offerLayout.addView(offerItem.getView());
}
}
Но я получаю исключение нулевого указателя в строке
offerItem.getView()
Как я могу сделать это правильно?
Ответ №1:
Добавьте FrameLayout к вашему первому фрагменту, а затем добавьте фрагмент в этот framelayout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@ id/parent"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="220dp"
android:background="#468494">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@ id/horizontalScrollView"
android:background="#BB099D"
android:layout_marginTop="15dp" >
<LinearLayout
android:id="@ id/child"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/black">
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Затем в вашем коде добавьте фрагмент в представление, используя FragmentManager
и FragmentTransaction
public class MainActivity extends Activity {
Fragment f;
EditText send;
LinearLayout parent;
LinearLayout child;
HorizontalScrollView scroll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup vg = (LinearLayout) inflater.inflate(R.layout.activity_main, null );
child = (LinearLayout) vg.findViewById(R.id.child);
loadSelectedOffers();
setContentView(vg);
}
private void loadSelectedOffers() {
for(int i=0;i<3;i )
{
FrameLayout frame = new FrameLayout(this);
child.addView(frame);
frame.setId(i);
frame.setBackgroundColor(getResources().getColor(R.color.black));
frame.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
SenderFragment offerItem = new SenderFragment();
transaction.add(i, offerItem, "offer_item_" );
transaction.commit();
}
}
Я считаю, что что-то подобное должно сработать сейчас.
Комментарии:
1. Спасибо за ваш ответ. Этот ответ работает, но это не то, что я ищу. Этот блок кода добавляет один OfferItemFragment поверх другого. Но мне нужно один за другим в режиме прокрутки в виде горизонтального списка.
2. Знаете ли вы, сколько элементов у вас будет в вашем представлении? Будет ли это 3?
3. Итак, я все еще думаю о способе динамической загрузки страниц, как вам нужно. Но альтернативой вместо использования scrollview было бы использование listview с горизонтальной ориентацией. Вы могли бы использовать OfferLayout для создания каждого элемента внутри listview и заполнения данных таким образом
4. Поцарапайте эту идею. Я не верю, что вы действительно можете создать горизонтальный список.
5. Я полагаю, что у меня есть ответ, который на самом деле будет делать то, что вы хотите сделать. Я обновил его, чтобы отразить эти изменения. Дайте мне знать, работает ли это для вас или нет.
Ответ №2:
Вы получаете view null, потому что его функция onCreateView() еще не была выполнена, что, в свою очередь, связано с тем, что вы просто создали экземпляр фрагмента и не привязали его к своей активности. Попробуйте добавить FrameLayouts в свой HSV и заменить их фрагментами.