2014-06-19 2 views
0

간단히 말해서, 나는 이름 목록을 검색하는 API 호출을 만들고 있습니다.API 호출 및 프로그래밍 방식으로 버튼 추가

검색된 각 이름에 대해 RelativeLayout (일부 자식 포함)을 부모 LinearLayout에 추가하고 싶습니다. 상대적 레이아웃은 다음과 같습니다

<RelativeLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/border_bottom" 
    android:clickable="true"> 

    <ImageView 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:layout_weight="11.79" 
     android:background="#58585a" 
     android:id="@+id/imageView" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="Large Text" 
     android:id="@+id/textView2" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="26dp" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceSmall" 
     android:text="Small Text" 
     android:id="@+id/textView3" 
     android:layout_below="@+id/textView2" 
     android:layout_alignStart="@+id/textView2" /> 

</RelativeLayout> 

내가 서버를 쿼리에서받은 일부 데이터에 '작은 텍스트'와 '큰 텍스트'필드를 변경하고 싶습니다.

이 작업을 수행하는 가장 좋은 방법은 무엇입니까? 위의 레이아웃을 별도의 XML 파일에 저장하고 텍스트 값을 빠르게 변경하고 기존 선형 레이아웃에 드롭 할 수 있습니까?

+3

이것은 'ListView'에 대한 교과서처럼 보입니다. 대신 하나를 사용 해본 적이 있습니까? – matiash

+0

그랬지만 몇 가지 이유 때문에 필자의 유스 케이스에 맞지 않습니다. 이 경우에는 DB에서 가져온 각 항목에 대해 위 코드를 삽입하려는 LinearLayout이 포함 된 ScrollView가 있습니다. – opticon

+0

그래도 여전히 'ListView'에 대한 교과서 같은데 ... :) 글쎄, 기술적으로 접근하면 효과가 있지만, 'ListView'가 이미하는 것처럼 보인다. 어린이보기, 재사용, & c). – matiash

답변

1

목록 1 : 각 목록 항목의 레이아웃

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="wrap_content" > 

    <ImageView 
    android:id="@+id/listImage" 
    android:layout_width="100dp" 
    android:layout_height="100dp" 
    android:layout_alignParentLeft="true" 
    android:layout_centerVertical="true" 
    android:layout_margin="10dp" 
    android:background="#ffcccccc" /> 

    <TextView 
    android:id="@+id/listTitle" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignTop="@+id/listImage" 
    android:layout_toRightOf="@+id/listImage" 
    android:text="A List item title" 
    android:textSize="16sp" 
    android:textStyle="bold" /> 

    <TextView 
    android:id="@+id/listDescription" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/listTitle" 
    android:layout_marginTop="5dp" 
    android:maxLines="4" 
    android:layout_toRightOf="@+id/listImage" 
    android:text="The List item description" 
    android:textSize="14sp" />  
</RelativeLayout> 

목록 2 :

,536 : -

public class DynamicListViewActivity extends ListActivity { 

     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.list);        

      ImageListAdapter adapter = new ImageListAdapter(this); 
      setListAdapter(adapter);         

      LoadFeedData loadFeedData = new LoadFeedData(adapter); 
      loadFeedData.execute();          
     } 
} 

목록 4 동적 ListView에에 대한

ListActivity :

<?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:gravity="center" android:orientation="vertical" > <ListView android:id="@android:id/list" android:fadingEdge="vertical" android:fadingEdgeLength="10dp" android:longClickable="true" android:listSelector="@drawable/list_selector_background" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> <!-- --> <TextView android:id="@android:id/empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Loading feed data..." /> <!-- --> </LinearLayout> #1 Listview with id of "list" #2 TextView with id of "empty" 

목록 3

- 목록보기를 포함하는 레이아웃

XML 피드 데이터를로드하는 데 사용

LoadFeedData 클래스 -

public class LoadFeedData extends 
      AsyncTask<void, void,="" arraylist<entry="">> {  

     private final String mUrl =        
     "URL_QUERING_TO_SERVER"; 

     private final ImageListAdapter mAdapter; 

     public LoadFeedData(ImageListAdapter adapter) {   
      mAdapter = adapter; 
     } 

     private InputStream retrieveStream(String url) { 
      DefaultHttpClient client = new DefaultHttpClient(); 
      HttpGet httpGet = null; 
      httpGet = new HttpGet(url); 

      HttpResponse httpResponse = null; 
      try { 
      httpResponse = client.execute(httpGet); 
      HttpEntity getResponseEntity = httpResponse.getEntity(); 
      return getResponseEntity.getContent(); 
      } catch (IOException e) { 
      httpGet.abort(); 
      } 
      return null; 
     } 

     @Override 
     protected ArrayList<Entry> doInBackground(Void... params) { 
      InputStream source = retrieveStream(mUrl);     
      Reader reader = null; 
      try { 
      reader = new InputStreamReader(source); 
      } catch (Exception e) { 
      return null; 
      } 
      Gson gson = new Gson(); 
      SearchResult result = gson.fromJson(reader,SearchResult.class);  
      return result.getFeed().getEntry(); 
     } 

     protected void onPostExecute(ArrayList<Entry> entries) { 
      mAdapter.upDateEntries(entries);      
     } 
} 

목록 5 : 데이터와 이미지와 ListView를 채우는 데 사용

ImageListAdapter -

public class ImageListAdapter extends BaseAdapter { 

     private Context mContext; 

     private LayoutInflater mLayoutInflater;        

     private ArrayList<Entry> mEntries = new ArrayList<Entry>();   

     private final ImageDownloader mImageDownloader;      

     public ImageListAdapter(Context context) {       
      mContext = context; 
      mLayoutInflater = (LayoutInflater) mContext 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      mImageDownloader = new ImageDownloader(context); 
     } 

     @Override 
     public int getCount() { 
      return mEntries.size(); 
     } 

     @Override 
     public Object getItem(int position) { 
      return mEntries.get(position); 
     } 

     @Override 
     public long getItemId(int position) { 
      return position; 
     } 

     @Override 
     public View getView(int position, View convertView, 
      ViewGroup parent) {           
      RelativeLayout itemView; 
      if (convertView == null) {           
      itemView = (RelativeLayout) mLayoutInflater.inflate(
         R.layout.list_item, parent, false); 

      } else { 
      itemView = (RelativeLayout) convertView; 
      } 

      ImageView imageView = (ImageView) 
      itemView.findViewById(R.id.listImage);       
      TextView titleText = (TextView) 
      itemView.findViewById(R.id.listTitle);       
      TextView descriptionText = (TextView) 
      itemView.findViewById(R.id.listDescription);     

      String imageUrl = mEntries.get(position).getContent().getSrc(); 
      mImageDownloader.download(imageUrl, imageView);     

      String title = mEntries.get(position).getTitle().get$t(); 
      titleText.setText(title); 
      String description = 
      mEntries.get(position).getSummary().get$t(); 
      if (description.trim().length() == 0) { 
      description = "Sorry, no description for this image."; 
      } 
      descriptionText.setText(description); 

      return itemView; 
     } 

     public void upDateEntries(ArrayList<Entry> entries) { 
      mEntries = entries; 
      notifyDataSetChanged(); 
     } 
} 

우수함, ! 이렇게하면 서버에서 동적 데이터를로드하고이를 listview에 표시합니다. 분명히, 응용 프로그램에 맞게 추가하기 위해 일부 또는 그 이상을 변경할 수 있습니다. 건배!

+0

나는 이것을 약간 수정해야했지만 이것이 올바른 길로 나를 잡았습니다! 감사! – opticon

0

10 가지 이상의 항목이 포함 된 목록을받은 경우이 방법을 사용하면 앱의 성능이 매우 저하됩니다. 사용자 지정 어댑터와 함께 ListView를 사용하여 모든 목표를 달성 할 수있는 확률은 99 %입니다. 이 경우 화면에 표시되는 경우에만 안드로이드가보기를 만듭니다. 귀하의 경우에는 필요하지 않더라도보기가 존재합니다.

아직 방법을 사용하고 싶다면이 ID로 TextView를 찾고 텍스트를 변경하십시오.

대략적인 코드

... 
LayoutInflater inflater = LayoutInflater.from(getContext()); 
customView = inflater.inflate(%Your_layout_id%, null); // Put id of your xml layout file 

largeTextView = (TextView)customView.findViewById(R.id.textView2); 
largeTextView.setText(%your_large_text%); 
TextView smallTextView = (TextView)customView.findViewById(R.id.textView3); 
smallTextView.setText(%your_small_text%); 
... 
관련 문제