Сбой при попытке найти ViewById для вложенного TextView (в ListView) - PullRequest
1 голос
/ 31 июля 2010

Попытка создать ListView (прокручиваемый список) строк, состоящих из двух TextView.У меня есть список элементов из базы данных, которые я хочу заполнить в LinearLayout-> ListView-> TextView, но не могу добраться до идентификатора ...

Макет в некоторой степени похож на эту учебную ссылку, но поддержалот RelativeLayout и использование LinearLayout, чтобы заставить его работать.Даже не беспокоится о том, как это выглядит;просто пока не могу соединить его.

http://android -developers.blogspot.com / 2009/02 / android-layout-tricks-1.html

Имеют два XML-файла (очень сокращенные подробности ниже) main.xml и stuff.xml

main.xml имеет

... TextView

... ListView

stuff.xml имеет

... android: id = "@ + id / firstLine"

... android: id = "@ + id / secondLine"

ДА, я делаю setContentView (R.layout.main);сразу после onCreate.

Получение нулевого значения для findViewByID (firstLine) и findViewID (secondLine).

У меня есть ArrayAdapter, где я раздуваю stuffView.Мое мышление и понимание других примеров заключается в том, что он не раздут (это вложенный материалViewView), пока я не намеренно надул его.Это все работает нормально, но когда я выполняю findViewById, он возвращает null, и поэтому я не могу установить setText ().

epic Fail из-за полного незнания / новизны с моей стороны.Примечание: я перебрал все, что могу, из книги Рето, особенно пример с похожим примером на странице 163, но неудача неудача неудача ...

Может ли какая-то добрая душа направить меня в правильном направлении?

Должен ли я раздуть это вложенное представление?(Пример Reto делает).Если так, что я пропускаю?Я надеюсь, что кто-то может указать мне лучший пример.Мой код, вероятно, слишком занят для публикации и немного запатентован.

Спасибо

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
 <TextView 
android:id="@+id/identText"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:text="some text here"

  />
 <ListView 
    android:id="@+id/myListView"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
  />

 </LinearLayout>

thing_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView 
android:id="@+id/identText"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:text="some text here"

  />
 <ListView 
    android:id="@+id/myListView"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
  />

</LinearLayout>

Pojo под названием Thingy (здесь не копируется Thingy.java - очень просто)

Основной класс: ShowLayoutNicely.java

package com.blap.test;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;

public class ShowLayoutNicely extends Activity {
 ListView myListView;
 TextView myTextView;

ArrayList<Thingy> thingys;

ThingyAdapter aa;


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

    myListView = (ListView) findViewById(R.id.myListView);
    myTextView = (TextView) findViewById(R.id.identText);

    thingys = new ArrayList<Thingy>();

    aa = new ThingyAdapter(this, android.R.layout.simple_list_item_1, thingys);
    myListView.setAdapter(aa);

// real deal has a call to go find items from database, populate array and notify of change.      
    Thingy thing1 = new Thingy("first", "first row");
    thingys.add(thing1);
// sadly - this isn't triggering getView() which I've overriden...
    aa.notifyDataSetChanged();

    Thingy thing2 = new Thingy("second", "second row");
    thingys.add(thing2);
    aa.notifyDataSetChanged();

}
}

Класс переопределения адаптера ThingyAdapter.java

package com.blap.test;

import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;


public class ThingyAdapter extends ArrayAdapter<Thingy> {

int resource;

public ThingyAdapter (Context _context, int _resource, List<Thingy> _items){
super( _context, _resource, _items);
resource = _resource;

}

@Override
public View getView(int position, View convertView, ViewGroup parent)  {
LinearLayout thingView;

Thingy thingItem = getItem(position);

String identString = thingItem.getIdent();
String nameString =thingItem.getName();

if (convertView == null){
    thingView= new LinearLayout(getContext());
    LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View nuView = vi.inflate(resource, thingView, true);

}
else{
    thingView = (LinearLayout) convertView;

}
//here's the problem - these calls return nulls.
TextView row1 = (TextView)thingView.findViewById(R.id.firstLine);
TextView row2 = (TextView)thingView.findViewById(R.id.secondLine);

//and naturally these puke ingloriously....
row1.setText(thingItem.getIdent());
row2.setText(thingItem.getName());
return thingView;
}
}

Так что этот код по сути то, что я ищу помощи;стерилизовать имена, чтобы назвать его Thingy .... Этот пример не вызывает getView ().Это второстепенная проблема, которую я должен решить.Что еще более важно, ваша помощь в сбое findViewById и, если я правильно понял XML, очень помогли бы.

1 Ответ

1 голос
/ 31 июля 2010

Когда вы надуваете свой макет, вы можете использовать findViewById на макете, который вы надуваете, так как я не знаю, каков ваш код, вот пример того, что я бы сделал:

 LayoutInflater li = LayoutInflater.from(mContext);
 LinearLayout mLayout = (LinearLayout) li.inflate(R.layout.stuff,null);
 View mView = mLayout.findViewById(R.id.firstLine);

Вы, вероятно, хотите, чтобы ваш null был родителем, который вы хотите иметь в своем раздутом макете.Надеюсь, это поможет!

Обновление

Я бы попробовал заменить то, что у вас есть:

thingView= new LinearLayout(getContext());
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View nuView = vi.inflate(resource, thingView, true);

на:

LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
thingView = vi.inflate(R.layout.thing_item, null);

Поскольку вы, кажется, делаете новую линейную планировку без причины, ваша инфляция уже будет иметь линейную компоновку из вашего XML-файла.Это в значительной степени то, что я сказал выше, и это работает для меня:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...