0

Я пытаюсь реализовать панель в фрагменте, который может расширяться при нажатии кнопки с правой стороны экрана. Я не могу использовать навигационный ящик, потому что у меня уже есть навигационные ящики как с левой, так и с правой стороны.Как сдвинуть LinearLayout при расширении SlidingDrawer?

Идея заключается в том, чтобы добиться чего-то вроде этого:

enter image description here

я был почти в состоянии сделать это с SlidingDrawer виджета (это не рекомендуется ..), единственная проблема в том, что я не знаю как заставить LinearLayout появляться в середине, а затем сдвигаться, когда нажата кнопка для расширения SlidingDrawer.

У меня есть следующий код:

public class MainActivity extends AppCompatActivity { 

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

     Button handle = (Button) findViewById(R.id.handle); 
     SlidingDrawer drawer = (SlidingDrawer) findViewById(R.id.slidingDrawer); 

     drawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() { 
      @Override 
      public void onDrawerOpened() { 
      } 
     }); 

     drawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() { 
      @Override 
      public void onDrawerClosed() { 
      } 
     }); 
    } 
} 

И в XML код:

<?xml version="1.0" encoding="utf-8"?> 
<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" 
    tools:context="com.test.slidingdrawertest.slidingdrawertest.MainActivity"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:gravity="center" 
     android:orientation="vertical"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="TEST TEST TEST" /> 

    </LinearLayout> 

    <LinearLayout 
     android:layout_alignParentEnd="true" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent"> 


     <SlidingDrawer 
      android:id="@+id/slidingDrawer" 
      android:layout_width="200dp" 
      android:layout_height="400dp" 
      android:layout_marginTop="100dp" 
      android:layout_gravity="end" 
      android:content="@+id/content" 
      android:handle="@+id/handle" 
      android:orientation="horizontal"> 

      <Button 
       android:id="@+id/handle" 
       style="?android:attr/borderlessButtonStyle" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Expand" /> 

      <LinearLayout 
       android:id="@+id/content" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="vertical"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="TEST TEST TEST" /> 

      </LinearLayout> 

     </SlidingDrawer> 

    </LinearLayout> 

</RelativeLayout> 
+0

Ваш LinearLayout должен идти влево, а затем становиться меньше, когда другой приближается к нему? Как сжатый между вашей расширенной панелью и левым пределом – king

+0

@Tritri Да, это так. Я пытаюсь изменить гравитацию «LinearLayout», но безуспешно. На данный момент я получаю «java.lang.ClassCastException: android.widget.RelativeLayout $ LayoutParams не может быть отброшен в android.widget.LinearLayout $ Исключение LayoutParams', когда я пытаюсь получить« LinearLayout »и изменять параметры. – Apostrofix

+0

I подумайте об этой ошибке, потому что ваш LinearLayout зависит от RelativeLayout так: 'RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams (RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); 'И гравитация, которую вы установили, предназначена для textView, а не для самого линейногоLayout, а layout_gravity будет работать, если вы будете в LinearLayout. Но даже с этим я не могу, если бы он мог работать. Я бы сделал что-то еще с кодом. – king

ответ

0

мне удалось делай это, на самом деле это было не так сложно, но это немного сложно. Вот решение:

XML-код:

<?xml version="1.0" encoding="utf-8"?> 
<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:id="@+id/topLayout" 
    tools:context="com.test.slidingdrawertest.slidingdrawertest.MainActivity"> 

    <LinearLayout 
     android:id="@+id/mainLayout" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:orientation="vertical"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="TEST" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_alignParentEnd="true" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent"> 

     <SlidingDrawer 
      android:id="@+id/slidingDrawer" 
      android:layout_width="200dp" 
      android:layout_height="400dp" 
      android:layout_marginTop="100dp" 
      android:layout_gravity="end" 
      android:content="@+id/content" 
      android:handle="@+id/handle" 
      android:orientation="horizontal"> 

      <Button 
       android:id="@+id/handle" 
       style="?android:attr/borderlessButtonStyle" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Expand" /> 

      <LinearLayout 
       android:id="@+id/content" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="vertical"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="TEST TEST TESTT" /> 

      </LinearLayout> 
     </SlidingDrawer> 
    </LinearLayout> 
</RelativeLayout> 

Код в MainActivity.java:

public class MainActivity extends AppCompatActivity { 

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

     Button handle = (Button) findViewById(R.id.handle); 
     SlidingDrawer drawer = (SlidingDrawer) findViewById(R.id.slidingDrawer); 
     final View k = findViewById(R.id.mainLayout); 

     drawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() { 
      @Override 
      public void onDrawerOpened() { 
       RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 
         RelativeLayout.LayoutParams.WRAP_CONTENT); 
       params.addRule(RelativeLayout.ALIGN_PARENT_TOP); 
       k.setLayoutParams(params); 
      } 
     }); 

     drawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() { 
      @Override 
      public void onDrawerClosed() { 
       RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 
         RelativeLayout.LayoutParams.WRAP_CONTENT); 
       params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); 
       k.setLayoutParams(params); 
      } 
     }); 
    } 
} 

И объяснение: я должен был дать Основное основной раскладке идентификатор (в формате XML) и затем найдите его в коде позади, тогда мне пришлось применить к нему новые параметры, когда ящик открывается или закрывается. В принципе, нам нужно найти родительский макет и установить для него параметры.

Теперь LinearLayout способен сдвинуть свое положение на выдвижном ящике и вернуться в исходное положение на выдвижном ящике. Следующий шаг - сделать этот процесс с анимацией, поэтому он плавный и не просто прыгает назад и вперед в новые позиции.

0

Вы можете изменить свой XML как этот

?xml version="1.0" encoding="utf-8"?> 
<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:padding="10dp" 
    tools:context="com.test.slidingdrawertest.slidingdrawertest.MainActivity"> 

    <LinearLayout 
     android:id="@+id/left"    // this is your linear layout 
     android:layout_width="match_parent" // that you want to shift left 
     android:layout_height="match_parent" 
     android:layout_toLeftOf="@+id/right" // apply this property due to 
    android:layout_alignParentLeft="true" //which if the width of sliding menu 
     android:gravity="center"    //increase it will automatically compressed 
     android:background="#aa00aa" 


     android:orientation="vertical"> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="TEST TEST TEST" /> 

    </LinearLayout> 

    <LinearLayout 
     android:id="@+id/right" 
     android:layout_alignParentRight="true" 
     android:layout_width="wrap_content" 
     android:background="#0000aa" 
     android:layout_height="match_parent"> 


     <SlidingDrawer 
      android:id="@+id/slidingDrawer" 
      android:layout_width="200dp"   // you can check by increasing or decreasing the with of this slidingdrawer 
      android:layout_height="400dp" 
      android:layout_marginTop="100dp" 
      android:layout_gravity="end" 
      android:content="@+id/content" 
      android:handle="@+id/handle" 
      android:orientation="horizontal"> 

      <Button 
       android:id="@+id/handle" 
       style="?android:attr/borderlessButtonStyle" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Expand" /> 

      <LinearLayout 
       android:id="@+id/content" 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="vertical"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="TEST TEST TEST" /> 

      </LinearLayout> 

     </SlidingDrawer> 

    </LinearLayout> 

</RelativeLayout> 

Помимо этого, если установить любую раскладку справа от вашей линейной компоновки, которая изначально GONE и при нажатии на кнопке его видимость изменилась на INVISIBLE/VISIBLE, поэтому он сдвинет линейный макет налево. Надеюсь, это поможет!

+0

Я не уверен, что я понимаю, что нужно установить справа от линейного макета. Не могли бы вы прояснить? – Apostrofix

+0

Просьба проверить отредактированный код с комментариями и сообщить мне, если есть какие-либо сомнения. –

+0

Благодарим вас за комментарии. Я пробовал это, но он не сдвигает левую линейную компоновку. Он остается статическим даже при расширении выдвижного выдвижного ящика, потому что ширина фиксируется при запуске приложения. – Apostrofix

0

Если вы хотите немного Exemple здесь мое решение: (я не знаю, если решение AVANI Нагар работает или нет):

TextView res; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_main); 

    final TextView img = (TextView)findViewById(R.id.second); 
    res = (TextView)findViewById(R.id.first); 

    img.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      img.setX(img.getX() - 5); 
      changew(img.getX()); 
     } 
    }); 
} 

private void changew(float w){ 
    res.getLayoutParams().width = (int)(res.getX() +w); 
    res.requestLayout(); 
    res.invalidate(); 
} 

XML-:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="@android:color/black"> 

<TextView 
    android:layout_toRightOf="@+id/first" 
    android:text="bonjourrrrrr" 
    android:id="@+id/second" 
    android:layout_width="wrap_content" 
    android:layout_height="100dp" 
    android:background="@android:color/holo_red_dark" /> 

<TextView 
    android:text="salutttttttt" 
    android:id="@id/first" 
    android:layout_width="wrap_content" 
    android:layout_height="100dp" 
    android:background="@android:color/holo_green_light" /> 


</RelativeLayout> 
Смежные вопросы