以编程方式调用API并添加按钮

时间:2014-06-19 07:29:05

标签: android

长话短说,我正在进行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文件中,并快速更改文本值,然后将其放入现有的线性布局中吗?

2 个答案:

答案 0 :(得分: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:

包含Listview的布局的XML -

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

动态列表视图的ListActivity -

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:

用于加载Feed数据的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:

ImageListAdapter用于使用数据和图像填充ListView -

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();
       }
}

大!这样,您将从服务器加载动态数据并将其显示在列表视图中。 显然,您可以更改其中的一些或更多以添加适合您的应用程序。 干杯!

答案 1 :(得分:0)

通过这种方法,如果您收到包含10个以上项目的列表,您的应用将具有非常低的性能。将ListView与自定义适配器一起使用可实现所有目标的概率为99%。在这种情况下,android只有在屏幕上显示时才会创建视图。在您的情况下,即使不需要,视图也会存在。

虽然如果您仍想使用您的方法,您可以通过此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%);
...