如何处理 ViewPager Tab 内的不同事件?
Posted
技术标签:
【中文标题】如何处理 ViewPager Tab 内的不同事件?【英文标题】:How to handle different events inside ViewPager Tab? 【发布时间】:2015-05-31 12:17:25 【问题描述】:我正在开发一个包含视图寻呼机的 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_
android:layout_>
</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_
android:layout_
android:orientation="horizontal"
android:background="@drawable/activity_background">
<ListView
android:id="@+id/lstItems"
android:layout_
android:layout_
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_
android:layout_
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_
android:layout_
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_
android:layout_
android:contentDescription="@string/img_desp"
android:src="@drawable/food_item_thumb" />
<RatingBar
android:id="@+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_
android:layout_
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_
android:layout_
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_
android:layout_
android:layout_alignBottom="@+id/imgIcon"
android:layout_alignLeft="@+id/txtPrice"
android:layout_alignTop="@+id/ratingBar" >
<ImageButton
android:id="@+id/imgPlus"
android:layout_
android:layout_
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_
android:layout_
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_
android:layout_
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_
android:layout_
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_
android:layout_
android:layout_alignRight="@+id/txtTitl"
android:layout_alignTop="@+id/txtTitl"
android:background="@drawable/label"
android:contentDescription="@string/img_desp" />
</RelativeLayout>
我想我已经提供了足够的信息来理解这个问题。 GeneralHelper 是一个从服务器获取 JSON 数据的 Web 服务类。 在这里,我想获取用户的订单详细信息。但我面临以下一些问题......
-
列表项不可点击,当我放事件处理代码时,它不起作用
如何处理 ImageButton(imgPlus 和 (imgMinus) 的 onClick 事件,它放置在 ListView 项中。我尝试使用 SwipeTabFragment.java 中的注释中编写的代码,但它也不起作用。
最后一个问题是,当我们向左或向右滑动时,标签切换得很好,但是如果我们点击标签,则无法切换。
请帮助我解决上述问题或其中任何一个问题。谢谢!
【问题讨论】:
你必须膨胀一个 LinearLayout 而不是 ListView 才能点击“+”和“-”的事件 并将这段代码放在 onTabSelected() 函数中:viewPager.setCurrentItem(tab.getPosition()); 谢谢@AvishekDas。你解决了我的第三个问题。标签运行良好。 请使用 LinearLayout 而不是 ListView。 您能否提供更多细节,如何膨胀线性布局?或者如果您有任何链接,请给我... 【参考方案1】:如何使用线性布局:
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:gravity="center" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_
android:layout_ >
<LinearLayout
android:id="@+id/layout1"
android:layout_
android:layout_
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</RelativeLayout>
提示.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_
android:layout_
android:orientation="vertical"
android:padding="10dp" >
<TextView
android:id="@+id/textView1"
android:layout_
android:layout_
android:text="Type Your Name : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="@+id/editTextDialogUserInput"
android:layout_
android:layout_ >
<requestFocus />
</EditText>
</LinearLayout>
行.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:orientation="vertical" >
<LinearLayout
android:id="@+id/layoutbg"
android:layout_
android:layout_
android:orientation="horizontal" >
<LinearLayout
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="@+id/img"
android:layout_
android:layout_
android:src="@drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/name"
android:layout_
android:layout_
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/num"
android:layout_
android:layout_
android:text="TextView" />
</LinearLayout>
<LinearLayout
android:layout_
android:layout_
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
<Button
android:id="@+id/del"
android:layout_
android:layout_
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(把它放在 assets 文件夹中)
"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 类。我希望您可以显示来自 URL 的图像。如果你能做到这一点,那么只需使用你的方法将图像从 URL 显示到 im ImageView...
只需使用这些文件创建一个新项目,您就会明白这一点..
【讨论】:
感谢@AvishekDas 的回复但是ImageLoader 和FriendBean 类呢?包含这些类的语句显示错误,因为它们没有在任何地方定义。我不知道这些类的结构。【参考方案2】:您在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();
;
【讨论】:
@KhanSquare 尝试更新的代码。看看您是否能够看到 Toast 消息。 在 rootView.findViewById(R.id.imgPlus).setOnClickListener(new View.OnClickListener() 它显示 NullPointerException !!在 toast 的上下文中,你通过“this”,我已经通过了活动实例 @KhanSquare 是的,这是意料之中的。它不会像这样运行。给你举个例子 无效!一切都和以前一样。我应该将此 itemClickListner 设置为控件吗?现在我只需粘贴这段代码并运行它。【参考方案3】:我得到了两个问题的解决方案。那是……
-
如何处理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;
-
当我们向左或向右滑动时,选项卡可以很好地切换,但是如果我们单击选项卡,则无法切换。
解决方案:我只需将以下行放在 onTabSelected() 中并让选项卡工作。这是@AvishekDas 建议的。再次感谢您。
@Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft)
viewPager.setCurrentItem(tab.getPosition());
但我仍然发现问题 1. 我的 listView 不可点击。如果你们中的任何人有解决方案,请发布。谢谢!
【讨论】:
以上是关于如何处理 ViewPager Tab 内的不同事件?的主要内容,如果未能解决你的问题,请参考以下文章
当ViewPager嵌套在ScrollView/ListView里时,手势冲突如何处理?
Actionscript:如何处理具有相同类型但具有不同函数侦听器的事件?