如何处理 ViewPager Tab 内的不同事件?

How to handle different events inside ViewPager Tab?

我正在开发一个包含视图寻呼机的 android 项目。 MenuActivity的UI如下...

下面是查看寻呼机活动的代码...

MenuActivity.java

public class MenuActivity extends FragmentActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;    
//  Tab titles
private String[] tabs;
private String[] category_id;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_menu);     
    CommonFunctions.changeActionBar(getResources(),getActionBar());
    //  Initialization
    initializeFoodCatagories();
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), tabs, category_id, MenuActivity.this);     
    viewPager.setAdapter(mAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);                
        }
    });     
    //Adding Tabs
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }
}   
private void initializeFoodCatagories() {
    GeneralHelper helper = new GeneralHelper();
    JSONObject json = helper.callWebService(getString(R.string.API_END_POINT) + "get_food_category");
    String total_items = helper.getValueFromJson(json, "TotalRecords");

    tabs = new String[Integer.parseInt(total_items)];       
    category_id = new String[Integer.parseInt(total_items)];

    if(!(total_items.equals("0"))) {
        try {
            final JSONArray jsonarray = json.getJSONArray("Response");
            for (int i = 0; i < jsonarray.length(); i++) {
                 JSONObject jsonobject = jsonarray.getJSONObject(i);                     
                 tabs[i] = jsonobject.getString("category_name").toString();                                                             
                 category_id[i] = jsonobject.getString("category_id").toString();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } 
    }       
}
@Override
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {      
}
@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {        
}
@Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}}

TabsPagerAdapter.java

public class TabsPagerAdapter extends FragmentPagerAdapter {
String [] category_name;    
String [] category_id;
Activity context;   
public TabsPagerAdapter(FragmentManager fm, String[] category_name, String[] category_id, Activity context) {
    super(fm);
    this.category_name = category_name;
    this.category_id = category_id;
    this.context = context;
}     
@Override
public Fragment getItem(int index) {
    for(int i = 0; i < category_name.length; i++) {
        if(index==i) { 
            return new SwipeTabFragment(context, category_id[i]);                                                                           
        }
    }       
    return null;
} 
@Override
public int getCount() {
    // get item count - equal to number of tabs
    return category_name.length;
}}

SwipeTabFragment.java

public class SwipeTabFragment extends Fragment {
Activity context;   
ListView list;
private String[] item_name;
private String[] price_per_unit;
private String[] item_image;
private String category_id;
public SwipeTabFragment(Activity context, String category_id) {
    this.context = context;
    this.category_id = category_id;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     
    View rootView = inflater.inflate(R.layout.activity_items, container, false); 
    list = (ListView) rootView.findViewById(R.id.lstItems);
    initializeFoodItems(category_id);
    list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
    //ListView event handling
    //This event not working
    /*list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","ListView activated");
        }
    });*/   
    //This event is also not working
    /*rootView.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","Plus Image Button activated");                
        }
    });*/
    return rootView;        
}       
private void initializeFoodItems(String position) {
    String url = getString(R.string.API_END_POINT) + "get_menu_items?food_cat_id="+position;

    GeneralHelper helper = new GeneralHelper();
    JSONObject json = helper.callWebService(url);

    String total_items = helper.getValueFromJson(json, "TotalRecords");
    price_per_unit = new String[Integer.parseInt(total_items)];
    item_name = new String[Integer.parseInt(total_items)];
    item_image = new String[Integer.parseInt(total_items)];


    if(!(total_items.equals("0"))) {
        try {
            final JSONArray jsonarray = json.getJSONArray("Response");
            for (int i = 0; i < jsonarray.length(); i++) {
                 JSONObject jsonobject = jsonarray.getJSONObject(i);
                 price_per_unit[i] = jsonobject.getString("price_per_unit").toString();
                 item_name[i] = jsonobject.getString("item_name").toString();                                        
                 item_image[i] = jsonobject.getString("item_image").toString();                  
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } 
    }       
}}

ItemListAdapter.java

public class ItemListAdapter extends ArrayAdapter<String> { 
static int grand_total;
private final Activity context; 
private final String title[];
private final String price[];
private final String discount[];    
public ItemListAdapter(Activity context, String[] title, String[] price,     String[] discount) {
    super(context, R.layout.item_list, title);
    this.context = context;
    this.title = title;
    this.price = price;
    this.discount = discount;
}       
@SuppressLint({ "ViewHolder", "InflateParams" })
@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    final View row = inflater.inflate(R.layout.item_list, null,true);       
    ((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
   final int item_price = Integer.parseInt(price[position]);
   ((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
    ((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
    RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
    LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
 stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange),     PorterDuff.Mode.SRC_ATOP);         
    //Increasing Quantity
    row.findViewById(R.id.imgPlus).setOnClickListener(new  View.OnClickListener() {
    @Override
    public void onClick(View v) {
        TextView qty = (TextView) row.findViewById(R.id.txtQty);
        qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
        if (Integer.parseInt(qty.getText().toString()) > 0) {               
            //Calculating Total Amount
            int t = item_price * Integer.parseInt(qty.getText().toString());
            ((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));                   
        }
    }
    });     
    //Decreasing Quantity       
    row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        TextView qty = (TextView) row.findViewById(R.id.txtQty);
        if (Integer.parseInt(qty.getText().toString()) > 0) {                   
            qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
            //Calculating Total Amount
            int t = item_price * Integer.parseInt(qty.getText().toString());
            ((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));               
        }               
    }
    });     
    return row;     
}
}

activity.menu.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

activity_items.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:orientation="horizontal"
    android:background="@drawable/activity_background">
    <ListView 
        android:id="@+id/lstItems"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:background="@drawable/listview_design"/>           
</RelativeLayout>

item_list.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"
android:orientation="horizontal"
android:background="@drawable/listview_design"
android:padding="5dp"
android:layout_margin="5dp" >
<TextView
    android:id="@+id/txtTitl"
    style="@style/ListViewHeader"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginLeft="8dp"
    android:layout_toRightOf="@+id/imgIcon"
    android:gravity="left"
    android:text="@string/itemname"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<ImageView
    android:id="@+id/imgIcon"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:contentDescription="@string/img_desp"
    android:src="@drawable/food_item_thumb" />

<RatingBar
    android:id="@+id/ratingBar"
    style="?android:attr/ratingBarStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imgIcon"
    android:layout_alignLeft="@+id/imgIcon"
    android:background="#80FF0000"
    android:numStars="5"
    android:paddingBottom="5dp"
    android:rating="3.5" />

<TextView
    android:id="@+id/txtPrice"
    style="@style/ListViewBottomText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtTitl"
    android:layout_below="@+id/txtTitl"
    android:paddingTop="0dp"
    android:text="@string/price_tag"
    android:textAppearance="?android:attr/textAppearanceMedium"
     />

<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="25dp"
    android:layout_alignBottom="@+id/imgIcon"
    android:layout_alignLeft="@+id/txtPrice"
    android:layout_alignTop="@+id/ratingBar" >

    <ImageButton
        android:id="@+id/imgPlus"
        android:layout_width="25dp"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:background="@drawable/sqr_plus"
        android:contentDescription="@string/img_desp" />

    <ImageButton
        android:id="@+id/imgMinus"
        android:layout_width="25dp"
        android:layout_height="match_parent"
        android:layout_alignBottom="@+id/imgPlus"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@drawable/sqr_minus"
        android:contentDescription="@string/img_desp" />

    <TextView
        android:id="@+id/txtQty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/imgPlus"
        android:layout_toRightOf="@+id/imgMinus"
        android:gravity="center_horizontal|center_vertical"
        android:text="@string/qty"
        android:textColor="#808080"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/TextView01"
        style="@style/ListViewBottomText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:gravity="center_horizontal|center_vertical"
        android:paddingBottom="0dp"
        android:paddingTop="0dp"
        android:text="@string/total"
        android:textColor="#AC2A2E"
        android:textSize="20sp" />

</RelativeLayout>

<ImageView
    android:id="@+id/imgDiscount"
    android:layout_width="30dp"
    android:layout_height="40dp"
    android:layout_alignRight="@+id/txtTitl"
    android:layout_alignTop="@+id/txtTitl"
    android:background="@drawable/label"
    android:contentDescription="@string/img_desp" />

</RelativeLayout>

我想我已经提供了足够的信息来理解这个问题。 GeneralHelper 是一项 Web 服务 class,用于从服务器获取 JSON 数据。 在这里,我想获取用户的订单详细信息。但是我面临着以下一些问题...

  1. 列表项不可点击,当我放置事件处理代码时,它不起作用
  2. 如何处理放置在ListView项中的ImageButton(imgPlus和(imgMinus))的onClick事件。我尝试了SwipeTabFragment.java中注释中写的代码,但它也不起作用。
  3. 最后一个问题是,当我们向左或向右滑动时,标签切换得很好,但是如果我们点击标签,则无法切换。

请帮我解决以上问题或其中任何一个。谢谢!

您在 onCreateView

中故意评论了 ListView 的 onItemclicklistener

取消注释代码

  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     
        View rootView = inflater.inflate(R.layout.activity_items, container, false); 
        list = (ListView) rootView.findViewById(R.id.lstItems);
        initializeFoodItems(category_id);
        list.setAdapter(new ItemListAdapter(context, item_name, price_per_unit));
        //ListView event handling



      list.setOnItemClickListener(itemClickListener );

        return rootView;        
    } 

ImageVIew 点击

在任何地方写这个方法

 // Item Click Listener for the listview
        OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                // Getting the Container Layout of the ListView
                RelativeLayout linearLayoutParent = (RelativeLayout ) container;

                // Getting the inner Linear Layout
                RelativeLayout linearLayoutChild = (RelativeLayout ) linearLayoutParent.getChildAt(1);

                // Getting the Country TextView
                ImageView iv = (ImageView) linearLayoutChild.getChildAt(0);

                Toast.makeText(getBaseContext(), "Image CLicked", Toast.LENGTH_SHORT).show();
            }
        };

线性布局的使用方法:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="400dp" >

    <LinearLayout
        android:id="@+id/layout1"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:orientation="vertical" >
    </LinearLayout>
</ScrollView>

</RelativeLayout>

prompts.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Type Your Name : "
    android:textAppearance="?android:attr/textAppearanceLarge" />

<EditText
    android:id="@+id/editTextDialogUserInput"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <requestFocus />

</EditText>

</LinearLayout>

row.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id="@+id/layoutbg"
    android:layout_width="fill_parent"
    android:layout_height="70dp"
    android:orientation="horizontal" >

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

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

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

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>

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

        <TextView
            android:id="@+id/num"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>

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

        <Button
            android:id="@+id/del"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="REMOVE" />
    </LinearLayout>
</LinearLayout>

</LinearLayout>

MainActivity.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.bean.FriendBean;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private LinearLayout mList;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
int loader = R.drawable.loader;
int i;
String val;

// public LayoutInflater inflater;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mList = (LinearLayout) findViewById(R.id.layout1);

    final ImageLoader img = new ImageLoader(getApplicationContext());

    StringBuffer sb = new StringBuffer();
    BufferedReader br = null;

    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open(
                "jsonarray.json")));
        String temp;
        while ((temp = br.readLine()) != null)
            sb.append(temp);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
        try {
            br.close(); // stop reading
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    String myjsonstring = sb.toString();

    try {
        JSONObject obj = new JSONObject(myjsonstring);
        JSONArray jsonarray = obj.getJSONArray("json");
        Log.e("Length", "" + jsonarray.length());
        for (i = 0; i < jsonarray.length(); i++) {
            JSONObject jsonObj = jsonarray.getJSONObject(i);
            String friend_name = jsonObj.getString("friend_name");
            String friend_phone = jsonObj.getString("friend_phone");
            String url = jsonObj.getString("image_url");
            FriendBean bean = new FriendBean(url, friend_name, friend_phone);
            arr.add(bean);
            Log.e("u", url);
            Log.e("friend_name", friend_name);
            Log.e("friend_phone", friend_phone);

            LayoutInflater vi = (LayoutInflater) getApplicationContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View v = vi.inflate(R.layout.row, null);

            final ImageView im = (ImageView) v.findViewById(R.id.img);
            final TextView t1 = (TextView) v.findViewById(R.id.name);
            final TextView t2 = (TextView) v.findViewById(R.id.num);
            final Button del = (Button) v.findViewById(R.id.del);
            img.DisplayImage(url, loader, im);
            t1.setText(friend_name);
            t2.setText(String.valueOf(i));
            mList.addView(v);

            t1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    LayoutInflater li = LayoutInflater.from(MainActivity.this);
                    View promptsView = li.inflate(R.layout.prompts, null);

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                            MainActivity.this);

                    // set prompts.xml to alertdialog builder
                    alertDialogBuilder.setView(promptsView);

                    final EditText userInput = (EditText) promptsView
                            .findViewById(R.id.editTextDialogUserInput);

                    userInput.setText(t1.getText().toString());

                    // set dialog message
                    alertDialogBuilder
                            .setCancelable(false)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                int id) {
                                            // get user input and set it to
                                            // result
                                            // edit text
                                            int f = Integer.parseInt(t2.getText()
                                                    .toString());
                                            Toast.makeText(getApplicationContext(),
                                                    "Position " + f, Toast.LENGTH_SHORT)
                                                    .show();
                                            val = userInput.getText().toString();
                                            Toast.makeText(getApplicationContext(),
                                                    val, Toast.LENGTH_SHORT).show();
                                            t1.setText(val);
                                            // mList.addView(v1);
                                            del.setOnClickListener(new OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    // TODO Auto-generated
                                                    // method
                                                    // stub
                                                    Toast.makeText(
                                                            getApplicationContext(),
                                                            "Previously "
                                                                    + mList.getChildCount(),
                                                            Toast.LENGTH_SHORT).show();
                                                    int f = Integer.parseInt(t2.getText()
                                                            .toString());
                                                    mList.removeViewAt(f);
                                                    Toast.makeText(
                                                            getApplicationContext(),
                                                            "Position "
                                                                    + t1.getText().toString(),
                                                            Toast.LENGTH_SHORT).show();
                                                    myFunction(mList);

                                                }
                                            });
                                        }
                                    })
                            .setNegativeButton("Cancel",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                int id) {
                                            dialog.cancel();
                                        }
                                    });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();

                    // show it
                    alertDialog.show();
                    Log.e("MSG", "HI");
                }
            });

            del.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(),
                            "Previously " + mList.getChildCount(),
                            Toast.LENGTH_SHORT).show();
                    int f = Integer.parseInt(t2.getText().toString());
                    mList.removeViewAt(f);
                    Toast.makeText(getApplicationContext(), "Position " + f,
                            Toast.LENGTH_SHORT).show();
                    myFunction(mList);
                }
            });

            im.setOnTouchListener(new OnTouchListener() {

                @Override
                public boolean onTouch(View arg0, MotionEvent arg1) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(),
                            t1.getText().toString(), Toast.LENGTH_SHORT).show();

                    return false;
                }
            });

        }

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public void myFunction(LinearLayout l) {
    LayoutInflater vi = (LayoutInflater) getApplicationContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.row, null);

    int c = l.getChildCount();
    for (int j = 0; j < c; j++) {
        v = l.getChildAt(j);
        TextView t2 = (TextView) v.findViewById(R.id.num);
        t2.setText(String.valueOf(j));
    }
    Toast.makeText(getApplicationContext(), "Finally " + c,
            Toast.LENGTH_SHORT).show();

}
}

jsonarray.json(将其放在资产文件夹中)

{ "json" : [ { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
    "friend_name" : "Madhumoy",
    "friend_phone" : "123"
  },
  { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
    "friend_name" : "Sattik",
    "friend_phone" : "123"
  },
  { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
    "friend_name" : "Koushik",
    "friend_phone" : "123"
  },
  { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
    "friend_name" : "Himanshu",
    "friend_phone" : "123"
  },
  { "image_url" : "http://www.ogmaconceptions.com/demo/NewsFeed/app_images/twitter_main.png",
    "friend_name" : "Sandy",
    "friend_phone" : "123"
  }
] }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.customlist"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.customlist.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

FriendBean.java

public class FriendBean {
private String Image;
private String name;
private String ph;

public FriendBean(String Image,String name,String ph){
    this.Image = Image;
    this.name = name;
    this.ph = ph;

}

public String getImage() {
    return Image;
}

public void setImage(String image) {
    Image = image;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPh() {
    return ph;
}

public void setPh(String ph) {
    this.ph = ph;
}



}

避免使用 ImageLoader class。我希望您可以显示来自 URL 的图像。如果你能做到,那么只需使用你的方法将图像从 URL 显示到 im ImageView...

只需使用这些文件创建一个新项目,您就会明白这一点..

我得到了两个问题的解决方案。那是...

  1. 如何处理放置在ListView项中的ImageButton(imgPlus和imgMinus)的onClick事件。我尝试使用 SwipeTabFragment.java 中注释中编写的代码,但它也不起作用。

解决方案: 我正在处理 ItemListAdapter.java 中的 onclick 事件,它工作正常。下面是这个文件的代码。这可能对其他人有帮助。

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.ArrayAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
public class ItemListAdapter extends ArrayAdapter<String> { 
static int grand_total;
private final Activity context; 
private final String title[];
private final String price[];
private final String discount[];    
public ItemListAdapter(Activity context, String[] title, String[] price, String[] discount) {
    super(context, R.layout.item_list, title);
    this.context = context;
    this.title = title;
    this.price = price;
    this.discount = discount;
}       
@SuppressLint({ "ViewHolder", "InflateParams" })
@Override
public View getView(int position, View view, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    final View row = inflater.inflate(R.layout.item_list, null,true);       
    ((TextView) row.findViewById(R.id.txtTitl)).setText(title[position]);
    final int item_price = Integer.parseInt(price[position]);
    ((TextView) row.findViewById(R.id.txtPrice)).setText(price[position] + " Rs. Each");
    ((TextView) row.findViewById(R.id.txtDiscount)).setText(discount[position] + "%");
    RatingBar ratingBar = (RatingBar) row.findViewById(R.id.ratingBar);
    LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
    stars.getDrawable(2).setColorFilter(row.getResources().getColor(R.color.orange), PorterDuff.Mode.SRC_ATOP);         
    //Increasing Quantity
    row.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView qty = (TextView) row.findViewById(R.id.txtQty);
            qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))+1));
            if (Integer.parseInt(qty.getText().toString()) > 0) {               
                //Calculating Total Amount
                int t = item_price * Integer.parseInt(qty.getText().toString());
                ((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));                   
            }
        }
    });     
    //Decreasing Quantity       
    row.findViewById(R.id.imgMinus).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TextView qty = (TextView) row.findViewById(R.id.txtQty);
            if (Integer.parseInt(qty.getText().toString()) > 0) {                   
                qty.setText(String.valueOf((Integer.parseInt(qty.getText().toString()))-1));
                //Calculating Total Amount
                int t = item_price * Integer.parseInt(qty.getText().toString());
                ((TextView) row.findViewById(R.id.txtTotal)).setText("Rs. " + String.valueOf(t));               
            }               
        }
    });     
    return row;     
}
}
  1. 当我们向左或向右滑动时,标签切换得很好,但是如果我们点击标签,则无法切换。

解决方案: 我只是将以下行放在 onTabSelected() 中并使选项卡工作。这是@AvishekDas 建议的。再次感谢。

@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {        
    viewPager.setCurrentItem(tab.getPosition());
}

But I'm still finding problem 1. My listView is not clickable. If any of you have solution then please post. Thank you!