2013-07-26 5 views
28

У меня есть FragmentActivity с этим макетом:получить вид родителя из макета

<?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" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/menulabel" 
    android:textSize="24sp" /> 

<EditText 
    android:id="@+id/editText1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:ems="10" 
    android:inputType="text" 
    android:layout_below="@+id/textView1" 
    android:hint="@string/search_title_hint" /> 

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/spinnersearch" 
    android:layout_below="@+id/editText1" /> 

<LinearLayout 
    android:id="@+id/layout1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/textView2" > 

    <Spinner 
     android:id="@+id/spinner_search" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:prompt="@string/spinnersearch" /> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/reset_search" /> 

</LinearLayout> 

<Button 
    android:id="@+id/button2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/buttonnewcat" 
    android:layout_below="@+id/layout1" /> 

<Button 
    android:id="@+id/button3" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/buttondelcat" 
    android:layout_below="@+id/button2" /> 

<Button 
    android:id="@+id/button4" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/buttoneditcat" 
    android:layout_below="@+id/button3" /> 

<Button 
    android:id="@+id/button5" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/buttonnewtext" 
    android:layout_below="@+id/button4" /> 

<Button 
    android:id="@+id/button6" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/buttondeltext" 
    android:layout_below="@+id/button5" /> 

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <side.menu.scroll.ScrollerLinearLayout 
     android:id="@+id/menu_content_side_slide_layout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:orientation="vertical" > 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="45dp" 
      android:background="@drawable/ab_solid_example" 
      android:orientation="horizontal" > 

      <ImageView 
       android:id="@+id/main_tmp_button" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:background="@drawable/actionbar_background" 
       android:src="@drawable/download" /> 

     </LinearLayout> 
     <FrameLayout 
      android:id="@+id/fragment_container" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:background="@drawable/bg_groud" /> 

    </side.menu.scroll.ScrollerLinearLayout> 
</RelativeLayout> 

и классом ScrollerLinearLayout что-то вроде этого:

public class ScrollerLinearLayout extends LinearLayout { 
    // code of the class 
} 

Как получить доступ из ScrollerLinearLayout к родительский макет для получения - например - editetxt? FragmentActivity и ScrollerLineraLayout находятся в разных пакетах тех же проектов. Я попытался использовать функцию getParent() таким образом в пределах ScrollerLinearLayout, но это не сработает.

RelativeLayout r = (RelativeLayout) this.getParent().getParent(); 
int w = r.findViewById(R.id.editText1).getLayoutParams().width; 

Кто-нибудь мне помогает? Благодаря!

+2

Что именно не работает? –

+0

@FD_ это nullpointerexception в 'RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()). GetParent();' –

+0

Где в 'ScrollerLinearLayout' вы вызываете этот код? –

ответ

59

Метод getParent возвращает ViewParent, а не View. Вы должны бросить первый вызов getParent() также:

RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()).getParent(); 

Как указано в комментариях по ОП, это вызывает NPE. Для отладки, разделить это на несколько частей:

ViewParent parent = this.getParent(); 
RelativeLayout r; 
if (parent == null) { 
    Log.d("TEST", "this.getParent() is null"); 
} 
else { 
    if (parent instanceof ViewGroup) { 
     ViewParent grandparent = ((ViewGroup) parent).getParent(); 
     if (grandparent == null) { 
      Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is null"); 
     } 
     else { 
      if (parent instanceof RelativeLayout) { 
       r = (RelativeLayout) grandparent; 
      } 
      else { 
       Log.d("TEST", "((ViewGroup) this.getParent()).getParent() is not a RelativeLayout"); 
      } 
     } 
    } 
    else { 
     Log.d("TEST", "this.getParent() is not a ViewGroup"); 
    } 
} 

//now r is set to the desired RelativeLayout. 
+0

Я пытался это сделать, но он не работает. ошибка является nullpointexception на RelativeLayout r = (RelativeLayout) ((ViewGroup) this.getParent()). getParent(); 'я не понимаю, что может быть ... –

+0

@ Rajin, я добавил раздел моего сообщения чтобы помочь вам отладить эту проблему. – Phil

+0

Я проверил журнал, и я обнаружил, что 'ViewParent parent = this.getParent();' возвращает null. У меня этот 'public class ScrollerLinearLayout расширяет LinearLayout {RelativeLayout r; // некоторый код public void init() {// ваш код}} 'правильный, когда я вызываю метод getParent()'? –

4

Если вы пытаетесь найти View от вашего Fragment затем попытайтесь сделать это так:

int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width; 
+0

метод 'getActivity()' не определен для типа ScrollerLineraLayout, который расширяет класс LinearLayout –

0

RelativeLayout (т.е. ViewParent) должен иметь идентификатор ресурса, определенный в файле макета (например, android:[email protected]+id/myParentViewId). Если вы этого не сделаете, вызов getId вернет значение null. Посмотрите на this answer для получения дополнительной информации.

-2

Просто напишите

this.getRootView(); 
+0

, это просто возвращает представление родительского восстания, а не фактический макет, как только один уровень родителя – Thecarisma

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